【问题标题】:Target WooCommerce product category archive pages from a child category term从子类别术语中定位 WooCommerce 产品类别存档页面
【发布时间】:2021-06-18 09:17:54
【问题描述】:

我对产品类别有疑问。我有一个这样的类别:

-electronic
-- laptop
-- mobile

然后我想为electronic下的所有产品创建一个逻辑,我使用is_product_category( ‘electronic’ ),但它不适用于电子产品,它仅在URL为mywebsite.com/product-category/electronic时有效,当我使用mywebsite.com/product-category/electronic/mobile/时它不起作用不行。我应该使用以下代码还是有其他选择:

is_product_category( ‘laptop’ )
is_product_category( ‘mobile’ )

【问题讨论】:

    标签: php wordpress woocommerce product taxonomy-terms


    【解决方案1】:

    您可以创建一个自定义条件函数来处理产品类别档案中的任何子产品类别,例如 (处理术语名称、术语 slug 或术语 ID)

    /**
     * Determines whether the query is for an existing product category archive page or for an ancestors product category archive page.
     *
     * @param int|string term ID, term slug or term name to check.
     * @return bool
     */
    function is_maybe_child_product_category( $category ){
        if( is_product_category( $category ) ) {
            return true;
        }
    
        $object = get_queried_object();
    
        if( ! is_a( $object, 'WP_Term') ) {
            return false;
        }
    
        $taxonomy = $object->taxonomy;
        $children = get_term_children( $object->term_id, $taxonomy );
        $result   = (array) term_exists( $category, $taxonomy );
    
        if( ! empty( $result ) ) {
            return false;
        }
        return in_array( reset($result), $children );
    }
    

    代码进入活动子主题(或活动主题)的functions.php 文件中。经过测试并且可以工作。

    用法:

    if ( is_maybe_child_product_category( 'laptop' ) ) {
        // Do something
    }
    

    【讨论】:

      【解决方案2】:

      您可以使用term_is_ancestor_of() 来检查当前正在查看的术语(产品类别)是否属于父术语。

      我写了一个简单的辅助函数:

      /**
       * @param int|object $parent ID or object term object to check.
       * @return bool Whether the product category being viewed is a child of the given parent category.
       */
      function wpse_is_child_product_category( $parent ) {
          if ( ! is_product_category() ) {
              return false;
          }
      
          return term_is_ancestor_of( $parent, get_queried_object(), 'product_category' );
      }
      

      用法:

      if ( is_product_category( 5 ) || wpse_is_child_product_category( 5 ) ) {
          // . . .
      

      【讨论】:

        猜你喜欢
        • 2018-12-09
        • 2020-11-25
        • 1970-01-01
        • 1970-01-01
        • 2021-09-03
        • 2019-07-20
        • 2019-12-25
        • 1970-01-01
        • 2017-03-27
        相关资源
        最近更新 更多