Layered Nav filters are a must have on your eCommerce website or easy to use online catalog. They give your visitors the ability to customize their engagement with your website to help them narrow down their product search hoping to find the one that matches their needs.
Unfortunately, simply adding a WooCommerce Layered Nav widget in the shop sidebar leaves your categories and subcategories with product filters where you don’t want to see them. Filters are generally used when you have a selection of products, not when looking at Subcategories.
The Solution
To make it work, you’ll need to work with three things:
- Widget Logic plugin
- Edit functions.php
- Use conditional logic statement in the WooCommerce Layered Nav widget
1. Download & Install the Widget Logic Plugin
You can install this plugin within WordPress > Plugins > Add New and search for “Widget Logic” and clicking install or by downloading it directly from its plugin page on WordPress.
2. Edit functions.php and Add this Custom Function
In your WordPress admin, go to Appearance > Edit and click on functions.php on the file list on the right. Scroll to the bottom of your file and add the follow lines of PHP code:
(I recommend editing your child theme’s function.php)
/*
* Purpose: Check if a Category has any Subcategories (Children)
* Returns: True or False
*/
function category_has_children() {
global $wpdb;
$term = get_queried_object();
$category_children_check = $wpdb->get_results(" SELECT * FROM wp_term_taxonomy WHERE parent = '$term->term_id' ");
if ($category_children_check) {
return true;
} else {
return false;
}
}
BTW, I found this code here, written by Matthew Price
3. Customize a WooCommerce Layered Nav Widget in Your Shop Sidebar
After you configure the attribute, in the Widget logic text area, use the following conditional statement:
!category_has_children()
4. Test it Now, See it in Action
Now, check your category and subcategory pages. You shouldn’t see any filter there. Then check a category without any subcategories and only products. You should only see the filter there.
Before
After
Here’s another example of using Layered Nav filters
Let me know if you found this tutorial useful by commenting or sharing it.
Leave a Reply