2016-06-22 91 views
1

我找到了一個WooCommerce代碼片段,它在類別頁面上添加了排序,並且它可以工作。WooCommerce:對子類別頁面上的類別/子類別也進行排序

但問題是,排序子類別僅顯示在父類別頁面上,而不顯示在子類別頁面中。

  • 這是分類頁面:

    Categories page

  • 的問題是,排序是不工作的子類別網頁:

    Sub category page

怎麼辦我需要改變我的代碼才能達到t帽子?

這裏是我的代碼:

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

+0

遺憾的延遲,這裏有一些截圖,這是我在我的父類別頁面中進行的子類別排序:http://prntscr.com/blpxtq 這是子類別頁面,問題是排序不是在其中顯示:http://prntscr.com/blpy48 – ssabin

+0

看到更多的調試結果會很有幫助。在子類別頁面上存儲到'$ terms'中的結果是什麼?這是你期望的嗎?並且'if'語句的條件返回true,以致它試圖創建無序列表? – PapaHotelPapa

+0

我做了一些調試。問題是我無法獲得子類別ID的父類別,當我使用get_queried_object_id();它給了我當前的類別,我如何使它給我的子類別父類別的ID? – ssabin

回答

0

好吧,我發現瞭如何做,所以我將與你分享:

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