• I am trying to add a custom setting at General Settings page with checkboxes.

    My plan to this is for users to select appropriate categories for their blog based on a list of categories through checkboxes.

    I use the code below.

    $new_general_setting = new new_general_setting();
    
    class new_general_setting {
        function new_general_setting( ) {
            add_filter( 'admin_init' , array( &$this , 'register_fields' ) );
        }
        function register_fields() {
            register_setting( 'general', 'mystore_categories', 'esc_attr' );
    		add_settings_field('mystore_categories', '<label for="main_admin">'.__('Store Category' , 'favorite_color' ).'</label>' , array(&$this, 'mystore_categories_func') , 'general' );
        }
        function mystore_categories_func() {
    	$options = get_option('mystore_categories');
    	$portfolio_cats = ( is_array( $options['mystore_categories'] ) ) ? array_map( 'absint', $options['mystore_categories'] ) : array();
     	$blog_id = 1;
    	switch_to_blog($blog_id);
        $hiterms = get_terms( 'product_category', array( 'hide_empty' => 0, 'parent' => 0) );
    
        foreach ($hiterms as $hiterm) {
          // $checked = $options[mystore_categories][$loterm->term_id] ? ' checked="checked"' : '';
          echo '<input type="checkbox" name="mystore_categories[]" value="' . $hiterm->term_id . '" ' . checked( in_array( absint( $hiterm->term_id ),$portfolio_cats ),true ) . '> ' . $hiterm->name . '<br/>';
    	  $loterms = get_terms('product_category', array('orderby' => 'slug', 'parent' => $hiterm->term_id, 'hide_empty' => 0));
    	  if($loterms) {
    	    foreach($loterms as $loterm) {
    	      echo '<input type="checkbox" name="mystore_categories[]" value="' . $loterm->term_id . '" style="margin-left:25px;" ' . checked( in_array( absint( $loterm->term_id ),$portfolio_cats ),true ) . '> ' . $loterm->name . '<br/>';
    	    }
    	  }
        }
    
        restore_current_blog();
    	echo '<br/><span class="description">Select the category or categories that suits what you sell.</span>';
        }
    }

    However, when submitting the page, the checked ones are not getting checked. Also, when I echo the $options[mystore_categories] its empty.

    Please help

The topic ‘[Settings API] Multiple Checkbox in General Settings’ is closed to new replies.