首页 文章

WooCommerce:也对子类别页面上的类别/子类别进行排序

提问于
浏览
1

我找到了一个WooCommerce代码片段,它在Category页面上添加了排序,并且它可以工作 .

但问题是排序子类别仅显示在父类别页面上,而不显示在子类别页面中 .

  • 这是类别页面:

Categories page

  • 问题是排序不适用于子类别页面:

Sub category page

为了达到这个目的,我需要在代码中进行哪些更改?

这是我的代码:

function tutsplus_product_subcategories( $args = array()) {
$parentid = get_queried_object_id(); 
$args = array(
    'parent' => $parentid
);

$terms = get_terms( 'product_cat', $args );

if ( $terms) {

    echo '<ul class="wooc_sclist">';

        foreach ( $terms as $term ) {

            echo '<li class="category">';                 


                echo '<h2>';
                    echo '<a href="' .  esc_url( get_term_link( $term ) ) . '" class="' . $term->slug . '">';
                        echo $term->name;
                    echo '</a>';
                echo '</h2>';

            echo '</li>';


        }

        echo '</ul>';
    }
}
add_action( 'woocommerce_before_shop_loop', 'tutsplus_product_subcategories', 50 );

参考:Display WooCommerce Categories, Subcategories, and Products in Separate Lists

1 回答

  • -1

    好吧,我发现了如何制作它,所以我将与你分享:

    function sub_fillter(){
            $sub = wp_get_post_terms(get_the_ID(),'product_cat');
            if ( is_subcategory()){
    
                $cat = array_shift( $sub );
                $cat=get_term_top_most_parent($cat->term_id,'product_cat'); 
                tutsplus_product_subcategories($cat);
            }
        }
            add_action('woocommerce_before_shop_loop', 'sub_fillter', 50);
    
    function is_subcategory (){
        $cat = get_query_var('cat');
        $category = get_category($cat);
        $category_gt_parent="";
        return ( $category_gt_parent == '0' ) ? false : true;
    }
    
    function tutsplus_product_subcategories( $cat) {
    $parentid = $cat->term_id; 
    $args = array(
        'parent' => $parentid
    );
    $terms = get_terms( 'product_cat', $args );
    
    if ( $terms || is_subcategory()) {
    
        echo '<ul class="wooc_sclist">';
    
            foreach ( $terms as $term ) {
    
                echo '<li class="category">';                 
    
                    echo '<h2>';
                        echo '<a href="' .  esc_url( get_term_link( $term ) ) . '" class="' . $term->slug . '">';
                            echo $term->name;
                        echo '</a>';
                    echo '</h2>';
    
                echo '</li>';
    
    
            }
    
            echo '</ul>';
        }
    }
    

相关问题