functions – Custom Settings Plugin Save foreach checkboxes

Question

I have these functions that create a form with checkoxes that come with each product attribute(i used a foreach loop) and I’m not sure where it goes wrong here.

I want to show all product attributes(like height, width, weight), and for each attribute there is a checkbox that need to be saved

I used this example to help -> https://themes.artbees.net/blog/custom-setting-page-in-wordpress/

function my_admin_menu() {
    add_menu_page(
        __( 'Hide attributes', 'my-textdomain' ),
        __( 'Hide attributes', 'my-textdomain' ),
        'manage_options',
        'hide-attribute',
        'my_admin_page_contents',
        'dashicons-schedule',
        14
    );
}
add_action( 'admin_menu', 'my_admin_menu' );

function my_admin_page_contents() {
    ?>
    <h1> <?php esc_html_e( 'Hide attributes.', 'my-plugin-textdomain' ); ?> </h1>
    <form method="POST" action="options.php">
    <?php
    settings_errors();
    settings_fields( 'hide-attribute' );
    do_settings_sections( 'hide-attribute' );
    submit_button();
    
    ?>
    </form>
    <?php
}

add_action( 'admin_init', 'my_settings_init' );

function my_settings_init() {

    add_settings_section(
        'hide_attribute_setting_section',
        __( 'Custom settings', 'my-textdomain' ),
        'hide-attribute'
    );

    add_settings_field(
        'hide_settings',
        __( 'Hide', 'my-textdomain' ),
        'my_setting_markup',
        'hide-attribute',
        'hide_attribute_setting_section'
    );

    register_setting( 'hide-attribute', 'hide_settings' );
    
}

loop through the product attributes and show a checkbox for each one

<?php
function my_setting_markup() {

    global $hide_options;

    $fbog_options = get_option('hide_settings');
    
    echo '<ul>';
    // Loop through WooCommerce registered product attributes
    foreach( wc_get_attribute_taxonomies() as $values ) {
        ?>
    <li>
    <input id="hide_settings_<?php echo $values->attribute_id; ?>" name="hide_settings[<?= $values->attribute_id ?>]" type="checkbox" value="1"<?php checked( 1, $hide_options && $hide_options[$values->attribute_id]); ?> />
    <label id="hide_settings_<?php echo $values->attribute_id; ?>"><?php echo $values->attribute_name ?></label>
    </li>
        
<?php
}
    echo '</ul>'
}

I’m using the attribute id to make each checkbox name and id unique.

Right now the checkbox options don’t save to the settings. I do see the success message but no checked boxes get saved.

What is the correct way to do this? Thanks

0
Sander105 3 weeks 2022-07-27T06:00:27-05:00 0 Answers 0 views 0

Leave an answer

Browse
Browse