【问题标题】:Check for a product category in a hooked function for WooCommerce products在 WooCommerce 产品的挂钩函数中检查产品类别
【发布时间】:2021-06-09 13:44:56
【问题描述】:

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

这是我的代码:

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

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

【问题讨论】:

    标签: php wordpress woocommerce hook-woocommerce taxonomy-terms


    【解决方案1】:
    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
    }
    

    【讨论】:

      【解决方案2】:

      您可以使用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 文件中。经过测试并且可以工作。

      【讨论】:

      • 我使用 get_the_terms(get_the_id(),'product_cat'); ,我希望它们是相似的。还是谢谢
      • @AmericanJewelry get_the_terms() 更重且处理起来更复杂,但也应该可以工作。
      猜你喜欢
      • 2019-06-20
      • 1970-01-01
      • 2018-12-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多