skip to Main Content

I want to check the category of WooCommerce products in function.php.

That is my code:

function for_preorder()
{
///// DISPLAY something if category id = 50 
}
add_action('woocommerce_before_single_product','for_preorder'); 

How to check for a product category for a WooCommerce product?

2

Answers


  1. if( has_term( 50, 'product_cat' ) ) {
     // do something if current product in the loop is in product category with ID 50
    }
    

    Or, if you pass the product ID in the for_preorder() function, you can do:

    if( has_term( 50, 'product_tag', 971 ) ) {
        // do something if product with ID = 971 has tag with ID = 50
    }
    
    Login or Signup to reply.
  2. You can use has_term() WordPress conditional function to check for a category like:

    add_action('woocommerce_before_single_product','for_preorder'); 
    function for_preorder() {
        global $product;
    
        $categories = array( 50 ); // Here define your categories term Ids, slugs or names
    
        if ( has_term( $categories, 'product_cat', $product->get_id() ) ) {
            echo '<p>' . __("DISPLAY something here") . '</p>';
        }
    }
    

    Code goes in functions.php file of the active child theme (or active theme). Tested and works.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search