在 WooCommerce 产品的挂钩函数中检查产品类别

问题描述

我想在 function.PHP 中查看 WooCommerce 产品的类别。

这是我的代码

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

如何检查 WooCommerce 产品的产品类别?

解决方法

您可以使用 has_term() WordPress 条件函数来检查以下类别:

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>';
    }
}

代码位于活动子主题(或活动主题)的functions.php 文件中。经测试有效。

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

或者,如果您在 for_preorder() 函数中传递产品 ID,您可以:

if( has_term( 50,'product_tag',971 ) ) {
    // do something if product with ID = 971 has tag with ID = 50
}