Dorokhov.codes
13. Options API
Retrieving options:
$my_option = get_option('my_option_name');
Updating options:
update_option('my_option_name', $new_value);
Deleting options:
delete_option('my_option_name');
Preparing data
Change data before saving.
add_filter( 'monthly_reports_service_account-gauges', [ $this, 'update_service_account_data' ], 10, 2 );
/**
* Update service account data.
*
* @param $new_value
* @param $old_value
* @return array
*/
public function update_service_account_data( $new_value, $old_value ): array
{
if ( isset( $_FILES[ 'monthly_reports_service_account' ] )
&& $_FILES[ 'monthly_reports_service_account' ][ 'error' ] == UPLOAD_ERR_OK ) {
$file_tmp_path = $_FILES[ 'monthly_reports_service_account' ][ 'tmp_name' ];
// Read the contents of the uploaded file
$file_contents = file_get_contents( $file_tmp_path );
// Decode the JSON data into a PHP array
$json_data = json_decode( $file_contents, true );
// Check if JSON decoding was successful
if ( $json_data === null ) {
return $old_value;
}
// Update the option with the extracted parameters
update_option( 'monthly_reports_service_account_data', $json_data );
// Return the updated array
return $json_data;
}
return $old_value;
}
Sync meta
Sync values between two meta.
$this->loader->add_filter( 'update_user_metadata', $plugin_public, 'sync_user_metadata', 10, 4 );
/**
* Sync user metadata.
*
* @return void
*/
public function sync_user_metadata( $check, $object_id, $meta_key, $meta_value ) {
if ( in_array( $meta_key, [ 'mepr_company_name', 'mepr_company_vat_number' ] ) ) {
$this->sync_meta_values(
'mepr_company_name',
'dismissed_wp_pointers',
$meta_key,
$meta_value,
$object_id
);
}
return $check;
}
/**
* Sync meta values.
*
* @param $meta_key_1
* @param $meta_key_2
* @param $current_meta_key
* @param $current_meta_value
* @param $user_id
* @return void
*/
protected function sync_meta_values( $meta_key_1, $meta_key_2, $current_meta_key, $current_meta_value, $user_id ): void
{
$synced_meta_key = ( $current_meta_key == $meta_key_1 ) ? $meta_key_2 : $meta_key_1;
if ( ! isset( $_REQUEST[ $synced_meta_key ] ) ) {
$this->update_user_meta( $user_id, $synced_meta_key, $current_meta_value );
}
}
/**
* Update user meta (custom function to avoid triggering hooks).
*
* @return void
*/
public function update_user_meta( $user_id, $meta_key, $meta_value ) {
global $wpdb;
$wpdb->query( $wpdb->prepare(
"UPDATE $wpdb->usermeta SET meta_value = %s WHERE user_id = %d AND meta_key = %s",
$meta_value,
$user_id,
$meta_key
) );
}