0

I created WordPress module, which adds my custom field in general settings in WordPress Admin. However after submitting whole form in admin settings, I need to modify my field's value before saving to database. How can I do that?

I would prefer to modify my field's data before any default WordPress form validation. Any clues? So far I spent on this hours, and could not google anything.

My code:

Located in my_module's main php file.

function my_module__section(){

    $settings_page_display = 'general';
    $section_id = 'my_module__section';
    add_settings_section(  
        $section_id,
        'Notification information',
        'my_module__section_description',
        $settings_page_display
    );

    $field_id = 'notification_text';
    $field_label = 'Name of customer';

    add_settings_field(
        $field_id,
        $field_label,
        'my_module__settings_fields_render',
        $settings_page_display,
        $section_id,
        [$field_id, 'text']
    );
    register_setting('general', $field_id, 'esc_attr');

}

function my_module__section_description() {
    echo '<p>Some description</p>';  
}

function my_module__settings_fields_render($args) {
    $field_id = $args[0];
    $field_type = $args[1];
    $option = get_option($field_id);
    echo '<input type="' . $field_type . '" id="'. $field_id .'" name="'. $field_id .'" value="' . $option . '" required>';
}

add_action('admin_init', 'my_module__section');

Note:

I am not searching for any frontend / javascript hacks - no exception.

  • It’s hard to comment without seeing your code – Andy Macaulay-Brook Mar 15 at 21:02
  • I updated answer with code preview. – Fusion Mar 15 at 21:17
1

If I got your question right then maybe you could try using the update_option action, which according to the docs "Fires immediately before an option value is updated.". It gets option, old value and new value as parameters. https://developer.wordpress.org/reference/hooks/update_option/

The accepted answer here, Hook if somebody saves plugin options?, might also be relevant for you.

If you feel adventurous, you could add a custom sanitize callback to register_setting and use it to do some funky stuff with the setting value. But this might be a little unorthodox way.

Personally I've found out that digging into the WP source code on trac is also a good way to find useful actions and filters for your custom functions. In this case for example the option.php https://core.trac.wordpress.org/browser/tags/5.1.1/src/wp-includes/option.php

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.