Tags

woocommerce-categories-featured-image

Here is the steps you need to follow to add product category on customizer without extending customize class:

  • Add section for the woocommerce  setting
  • add setting for the category
  • add select option on add control function
  • Create custom function to list category
  • create function for sanitization

add_action(‘customize_register’, ‘your theme_theme_customize’);
function your_theme_theme_customize($wp_customize) {

//create section
$wp_customize->add_section( ‘woocommerce_settings_home_feat’, array(
‘title’ => __( ‘HomePage Featured Produts’, ‘theme-domain’ ),
‘priority’ => 43,
‘panel’ => ‘woocommerce_setting_panel’

) );

//create setting
$wp_customize->add_setting( ‘woo_category’, array(
‘default’ => ‘select_category’,
‘sanitize_callback’ => ‘theme_get_categories_sanitize’
) );

//control setting for select options
$wp_customize->add_control( ‘woo_category’, array(
‘label’ => __( ‘Category’, ‘theme-domain’ ),
‘section’ => ‘woocommerce_settings_home_recent’,
‘type’ => ‘select’,
‘choices’ => theme_get_categories_select(),
‘priority’ => 6,
) );
}

Here is the  custom function to display all categories:

/**
*@description:function to retrieve all woocommerce product category
*@see for the get_terms functon https://developer.wordpress.org/reference/functions/get_terms/
*@see for the fucntion taxonomy_exists https://codex.wordpress.org/Function_Reference/taxonomy_exists
*/
function theme_get_categories_select() {
if ( taxonomy_exists ( ‘product_cat’ )) {
$results= array (‘select_category’=> ‘Select category’); // for default value
$teh_cats = get_terms(‘product_cat’, array ( ‘orderby’ => ‘count’, ‘include’ => ‘,’ ,’order’ => ‘DESC’));
$count = count($teh_cats);
for ($i=0; $i < $count; $i++) { if (isset($teh_cats[$i])) $results[$teh_cats[$i]->slug] = $teh_cats[$i]->name; //provide slug as options key and category name as options  value on select options
else
$count++;
}
return $results;
} else {
return array (“select_category” => __(‘Add Category’, ‘them text domain’)); // if woocommerce is not installed
}
}

Finally we need to sanitize the value of customizer.

/**
*@description:function to sanitize all woocommerce product category
*@since
*/

function theme_get_categories_sanitize ( $input ) {
$test = array();
$teh_cats = get_terms(‘product_cat’, array ( ‘orderby’ => ‘count’, ‘include’ => ‘,’ ,’order’ => ‘DESC’));
foreach ($teh_cats as $key => $the_cat) {

if ($input === $the_cat->slug) {
$test[] = $the_cat->slug;
}
}
if ($input == ‘select_category’) {
return ”;
} else {
return $test[0];
}
}

Here is the output for this:

woo select.png

Note: If you require any information or have any question or queries or you have better soution than this then please feel free to contact me at adhsushil7@gmail.com

Thanks

Advertisements