How to Check If Product Page In WooCommerce

woocommerce check if product pageAre you looking for a working WooCommerce check if product page code snippet? In this post, I share with you the snippet that will work for checking the WooCommerce single product template and explain why other approaches will not work as they do for WordPress single post.

WooCommerce Check If Product Page

If you are looking for a way to check if you are on a product page in WooCommerce, you most likely think you should use WordPress single post conditional tag something like is_single( ).

Unfortunately, this does not work with WooCommerce single page.

In this post, I want to guide you on how to check if you are on a product page in WooCommerce.

WordPress by default comes with several conditional tags that WordPress developers use to check if it’s a page, post, front page, and so on. The following are some of the most common conditional tags for WordPress pages ;

[php]

is_single( ‘1’ )

is_page( ‘1’ )

is_category( ‘1’ )

is_page_template( ‘about.php’ )

[/php]

For WooCommerce, the approach is different when you are using the single post ID.  You need to access the ID using the global product object instead of using the post global object.

Unlike the shop page that has a conditional tag that works  as shown in the code below :

[php]

if( is_shop() ) :

// code logic here

endif;
[/php]

For product category you can also use the conditional tag that is built in as in the code snippet below :

[php] if ( is_product_category() ) {

if ( is_product_category( ‘clothing’ ) ) {

} elseif ( is_product_category( ‘movies’ ) ) {

} else {

}

}
[/php]

For a single product, you need to check using the single product ID and this can be tricky since as earlier stated the global post object id will not work and you should therefore use the global product to access the current product ID as in the code below :

[php]

global $product;
if ( $product->get_id() == 1 ) {

// your logic here

}

[/php]

To test this code I have added it in an action hook and displayed on the header and when you visit the single product page you should see the message displayed at the top as shown on the image below:

check if product page

Conclusion

In this post, we have looked at how to check if the product page in WooCommerce uses the ID of the product. We have made a comparison with the default WordPress way of checking if single post page and how to change the access of the ID for it to work in WooCommerce.

Similar Articles

  1. How to Exclude Product From Discount Coupons WooCommerce