Check if a Product Belongs to a Product Category or Tag
In this post you will learn how you can check if one or more products belong to a Woocommerce category/tag with PHP. As commented in the code below, we want to check if the products belong to the category “TVs” and add a text if it is true. We also want to check if the product with the ID “29167” has the tag “Remove” and also add a text to the product if it is true.
This is how the product with the category “TVs” looks like before changing the code:
This is how the product with the specific ID and the tag “Remove” looks like before changing the code:
You can check the products and add the texts by adding the following code to your functions.php file:
add_action( 'woocommerce_before_single_product', 'arrow_design_category_tag_checks' ); function arrow_design_category_tag_checks() { if( has_term( 15, 'product_cat' ) ) { // Adds text to products with the category "TVs" which has the ID 15 echo '<p><strong>This product has the category TVs.</strong></p>'; }else if( has_term( 31, 'product_tag', 29167 ) ) { // Adds text to the product with the ID 29167 if it also has the Tag "Remove" which has the ID 31 echo '<p><strong>This product will be removed in two days, so be fast to buy it!</strong></p>'; } }
Conclusion
We hope this Check if a Product Belongs to a Product Category or Tag post was helpful and you are now able to integrate this also on your website! You can find more articles here:
Read another Woocommerce post : ‘Remove Customer Details from the Order Summary‘
Arrow Design, based in Dublin, Ireland, provides quality website design services in Dublin and beyond at affordable prices. If you would like help with implementing the above code, or any wordpress website development project, contact us. We love website design and it shows! We provide custom wordpress plugin development, website design training and lots more.
We do it all, so you don’t have to!
Related Posts
Woocommerce Account Page Hook Guide
In this article you will find a visual hook guide for the Woocommerce Account Pages, like the Login/Register page, the Downloads page or the Orders page.
Woocommerce Single Product Page Hook Guide
In this article you will find a visual hook guide for the Woocommerce Single Product Page. This should help you to quickly and easily find the hook positions on the page.
Woocommerce PHP – Product Categories by Product ID
In this tutorial you will learn how to check if a product is assigned to a tag, a category or a custom taxonomy. You can check if a product is is on the shop page, in the cart, in an order & more.
…We do more, so you can do less 🙂