vendredi 12 mai 2023

Sanitize multiple checkbox in Wordpress form

I'm creating Wordpress Plugin and i'm stuck with my checkbox's group. I want to sanitize it but when i add the sanitize_callback, my form do not save anything.

Here's my checkbox part

    function customPostTypeHTML() { 
            
        $args=array(
            'public'                => true,
            'exclude_from_search'   => false,
            '_builtin'              => false
        ); 
        
        $output = 'names';
        $operator = 'and'; 
        $post_types = get_post_types($args,$output,$operator);
        
        foreach ($post_types  as $post_type ) {
            
            <div>
                <input type="checkbox" name="asmsl_custom_post_type_page[<?php echo $post_type; ?>]" id="<?php echo $post_type; ?>" value="1" <?php checked(isset(get_option('asmsl_custom_post_type_page')[$post_type]), '1'); ?>>
                <label for="<?php echo $post_type; ?>"><?php echo ucfirst($post_type); ?></label> 
            </div>
        <?php }
        
    ?>
<?php }

Well, this checkbox is the pre-made wordpress form works well. I test it in a custom form, it works too.

In this example as I said, i use the wordpress form, so i add et register some settings to display it :

    add_settings_section('asmsl-custom-post-type_first_section',  esc_html__('Custom Post Type', 'asmsl_domain'), array($this, 'customPostTypeSection'), 'asmsl-custom-post-type');
    register_setting('customPostTypePage', 'asmsl_custom_post_type_page', array('sanitize_callback' => array($this, 'sanitizeCustomPostType'), 'default' => "0"));
    add_settings_field('asmsl_custom_post_type_page', esc_html__('Choose where to display your Social media', 'asmsl_domain'), array($this, 'customPostTypeHTML'), 'asmsl-custom-post-type', 'asmsl-custom-post-type_first_section');

Problem appears when i use the "array('sanitize_callback')". If I delete this part, my checkboxes are saving well..but I need to sanitize this checkboxes.

I tried many things, doing my own sanitize function but everytime I failed either : not saving data, or : saving data without sanitize anything.

Any suggestions ?




Aucun commentaire:

Enregistrer un commentaire