The Problem
When adding functionality to a WooCommerce store we sometimes want to add features that should only be present on category or tag pages. In this article, we’ll take a look at how we can detect category and tag pages in our WooCommerce code.
The Solution
This code will detect if the user is on a category page
Become a WooCommerce Coding Jedi
Click here for more details about the "Learning WooCommerce Development By Example" book
Click here for more details about the "Learning WooCommerce Development By Example" book
//returns true if the current page is a category page
is_product_category();
//returns true if the current page is the category page specified in the passed argument
is_product_category('shirts');
//returns true if the current page is any of the category pages specified
//in the passed array
is_product_category(array('shirts', 'games' ));
//also works with numerical ids
is_product_category(18);
is_product_category(18,19,20);
The code for detecting a tag page is very similar
Become a WooCommerce Coding Jedi
Click here to enroll in our Free WooCommerce Coding Course
Click here to enroll in our Free WooCommerce Coding Course
//returns true if the current page is a category page
is_product_tag();
//returns true if the current page is the tag page specified in the passed argument
is_product_tag('puzzles');
//returns true if the current page is any of the tag pages specified
//in the passed array
is_product_tag(array('jigsaws', 'toys' ));
//also works with numerical ids
is_product_tag(18);
is_product_tag(18,19,20);
Discussion
There’s not really an awful lot more to say about this as the code itself is pretty self-explanatory. If you do have any questions then please don’t hesitate to let us know in the comments.