3

I am used to register plugin settings like this:

$string_sanitization = array(
    'sanitize_callback' => 'sanitize_text_field',
);

// Section Setting: Just some example string
register_setting(
    'whatever',                // Options group name
    'some_example_string',     // Option ID
    $string_sanitization       // Sanitization callback
);

And it works perfect.

But when it comes to options that store arrays of strings, I don't know what to use.

The docs contain a types key for the args, but it's not clear enough, so I tried as follows:

register_setting(
    'whatever',                // Options group name
    'array_of_strings',        // Option ID
    array( 
       'type' => 'array',
       'sanitize_callback' => 'sanitize_text_field',
    )
);

In this case the options don't get saved.

One thing that works is to create a custom sanitization function that handles the array, as follows:

function sanitize_array_of_strings( $array ) {
    return array_map( 'sanitize_text_field', $array );
}

register_setting(
    'whatever',                // Options group name
    'array_of_strings',        // Option ID
    array( 
       'type' => 'array',
       'sanitize_callback' => 'My\Namespace\sanitize_array_of_strings',
    )
);

But it seems strange to me that WP does not have a native way to do this, so I ask to find out if you know of a native way to achieve this without having to create a custom function for that.

1
  • 3
    Your approach is correct. WordPress doesn't have a function for everything. Commented Aug 14, 2021 at 16:05

1 Answer 1

0

There actually is a WordPress function for this: map_deep( $value, $callback ).

This function iterates over all the elements in your array, even if they are arrays or objects.

Let's modify your code:

function sanitize_array( $array ) {
    return map_deep( $array, 'sanitize_text_field' );
}

register_setting(
    'whatever',                // Options group name
    'array_of_strings',        // Option ID
    array( 
       'type' => 'array',
       'sanitize_callback' => 'My\Namespace\sanitize_array',
    )
);

Although it looks almost the same as you had, this will take care as well of nested arrays and objects. So if your array is flat your function wouldn't encounter any issues, but if it happens to be nested or contain objects, those wouldn't be sanitized, but map_deep() takes care of it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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