Search code examples
wordpresssanitization

Data validation / Sanitization callback function


I added a section to the customizer of my WP theme that allows a user to change which categories display on the first page of the theme. However, when checking with the Theme Check plugin, it returned the following error:

REQUIRED: Found a Customizer setting that did not have a sanitization callback function. Every call to the add_setting() method needs to have a sanitization callback function passed. I have no idea how to add this function to my code. If you can help, here’s the code:

http://pastebin.com/xksf3vWd

Thanks in advance!


Solution

  • By default, the Customizer does not handle validation and sanitization of the user input values. It is therefore essential to sanitize these values before saving them to the database.

    The add_setting() method of the WP_Customizer object accepts an 'sanitize_callback' argument, that can be used to specify a sanitization callback. So, in every add_setting() call, add the sanitization callback function.

    $wp_customize->add_setting( 'first_category', array(
        'default'           => 'Uncategorized',     // The default category name.
        'sanitize_callback' => 'ys_sanitize_category',  // Sanitize callback function name
    ) );
    

    The Sanitize callback function:

    function ys_sanitize_category( $category ) {
        if ( ! in_array( $category, array( 'Uncategorized', 'Blogposts', 'News' ) ) ) { // Add the names of your categories here. Use get_categories() to fetch them dynamically.
            $category = 'Uncategorized';
        }
        return $category;
    }