Search code examples
phpwordpresswoocommercehook-woocommercetaxonomy-terms

Check for a product category in a hooked function for WooCommerce products


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?


Solution

  • 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.