How to Check If Current Page Is Category WordPress

Check If Current Page Is Category WordPressAre you searching endlessly for the best way to check if current page is category WordPress? If you want to check if the current page is a category page in your code, I will share with you the code and illustrate how you can get this done.

In most cases when you are creating a WordPress theme or plugin that involves using WordPress category templates, you will be required at one point to check if current page is category page in WordPress or WooCommerce.

It is important to understand that the way to check if current page is category in WooCommerce is slightly different from WordPress.

Let me begin with the latter to demonstrate how you can check outside the loop is current page in a category page.

Check If Current Page Is Category WordPress

In WordPress to check if the current page is a category page you need to use the function:

is_category( );

The general expression of this function is

is_category( int|string|int[]|string[] $category = ” )

This function takes in one parameter that can be an ID, slug or name of the category as shown in the description below:

Parameter Description 
$category (int|string|int[]|string[]) (Optional) Category ID, name, slug, or array of such to check against.

 

Default value: ‘ ‘

 

You can use the ID, slug, or name as in the code below:

 <br data-mce-bogus="1">

is_category();

is_category(‘10' ); // where 10 is category id

is_category(‘example' ); // where example is category name

is_category(‘example-slug' ); // where example-slug is category slug


Check If Current Page Is Category Page In WooCommerce

When you try using the function above in WooCommerce it will not work. Instead of is_category() function you should use is_product_category( )

You can get the ID of the WooCommerce category as follows :



$current_category = get_queried_object();

$id = $current_category->term_id;


You can now pass the ID to the function above and display the code in the header using a hook as shown in the image below:

The full code including the header hook is as follows :

 

add_action('wp_head', 'display_example_code_header');

function display_example_code_header(){

$current_category = get_queried_object();

//Print All the Data&nbsp; from category object

//print('<pre>');

//print_r($current_category);

//print('</pre>');

$id = $current_category->term_id;

if(is_product_category($id)){

echo "It is product category page";

}


Conclusion 

In this post, we have looked at how to check if the current page is a category page in WordPress as well as how to check it in WooCommerce. The take from this quick guide is how to use the two default WordPress functions that are used to check category pages in WordPress and WooCommerce respectively.

Similar Articles

  1. How to Migrate WordPress.com to WordPress.org