
Dynamically Setting Display Type for Categories in WooCommerce
- December 14, 2016
- Leave a comment
WooCommerce provides three types of display for content on category’s detail page such as Products, Subcategories, Both. By default, one of these three types is already selected. To change it, you can set another option from WooCommerce settings under Products tab. Additionally, you can set different options for each category. In this article, you will learn to set any one option dynamically without going to WooCommerce settings.
At first, you need to divide categories into two major ones like Parent and Children categories. Under child category page, you will be able to display products listing. Whereas under Parent category page, you will be able to display child categories.
In order to achieve this goal, you will use WordPress get_term_metadata filter. To access term meta, this filter is hooked with pt_set_category_display function in order to check if the category is either parent or child. Now, add the following code in your Theme‘s functions.php file or use it in your custom plug-in:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
<?php function pt_set_category_display( $value = null, $object_id, $meta_key, $single ){ // Get category of woocommerce $term = get_term( $object_id, 'product_cat' ); // If category exists and is child category if( is_object( $term ) && $term->parent > 0 && 'display_type' === $meta_key ){ $display_type = 'products'; } elseif( 'display_type' === $meta_key ){ // If category is parent $display_type = 'subcategories'; } else{ // else return nothing, this meta is not "display_type" return; } return ( true === $single ) ? $display_type : array( $display_type ); } // Attach function with wordpress filter add_filter( 'get_term_metadata', 'pt_set_category_display', 10, 4 ); |
User Comments