【问题标题】:List the subcategories of a given product category in Woocommerce在 Woocommerce 中列出给定产品类别的子类别
【发布时间】:2018-06-10 14:44:17
【问题描述】:

我在网上找到了各种 sn-ps 来列出 woocommerce 产品类别,但我找不到列出给定类别的子类别和子子类别的 sn-p。

如何获取给定产品类别的子类别?

【问题讨论】:

    标签: php wordpress woocommerce categories product


    【解决方案1】:

    这可以通过自定义函数实现,您可以在其中设置“父”产品类别 slug:

    function get_product_subcategories_list( $category_slug ){
        $terms_html = array();
        $taxonomy = 'product_cat';
        // Get the product category (parent) WP_Term object
        $parent = get_term_by( 'slug', $category_slug, $taxonomy );
        // Get an array of the subcategories IDs (children IDs)
        $children_ids = get_term_children( $parent->term_id, $taxonomy );
    
        // Loop through each children IDs
        foreach($children_ids as $children_id){
            $term = get_term( $children_id, $taxonomy ); // WP_Term object
            $term_link = get_term_link( $term, $taxonomy ); // The term link
            if ( is_wp_error( $term_link ) ) $term_link = '';
            // Set in an array the html formated subcategory name/link
            $terms_html[] = '<a href="' . esc_url( $term_link ) . '" rel="tag" class="' . $term->slug . '">' . $term->name . '</a>';
        }
        return '<span class="subcategories-' . $category_slug . '">' . implode( ', ', $terms_html ) . '</span>';
    }
    

    代码进入您的活动子主题(或活动主题)的 function.php 文件中。

    经过测试并且有效。


    用法示例:

    echo get_product_subcategories_list( 'clothing' );
    

    您将获得此给定类别的所有子类别的水平逗号分隔列表(带有链接)

    【讨论】:

    • 感谢 sn-p。但是,现在同时显示子类别和子子类别。我想在 ul 中有它的父类别下的子类别吗?我该怎么做?
    【解决方案2】:

    这是获取给定类别的子类别的代码:

     $categories = get_the_terms( get_the_ID(), 'product_cat' ); 
    
     //For checking category exit or not
    
     if ( $categories && ! is_wp_error( $category ) ) : 
    
    
       foreach($categories as $category) :
          // get the children (if any) of the current cat
          $children = get_categories( array ('taxonomy' => 'product_cat', 'parent' => $category->term_id ));
    
        if ( count($children) == 0 ) {
           // if no children, then echo the category name.
            echo $category->name;
        }
      endforeach;
    
     endif;
    

    【讨论】:

    • 对不起,我的小知识,但是我在哪里插入分类蛞蝓?
    猜你喜欢
    • 1970-01-01
    • 2017-06-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-06-27
    • 1970-01-01
    相关资源
    最近更新 更多