2017-08-17 76 views
1

有沒有什麼辦法讓在woocomerce頂級產品類別列表中自定義欄目我的主題獲得的頂級產品類別的自定義數組中WooCommerce

這裏中顯示他們是我使用的代碼,但它返回所有類別:

function getCategoriesList() { 

    // prior to wordpress 4.5.0 
    $args = array(
     'number'  => $number, 
     'orderby' => $orderby, 
     'order'  => $order, 
     'hide_empty' => $hide_empty, 
     'include' => $ids 
    ); 

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

    // since wordpress 4.5.0 
    $args = array(
     'taxonomy' => "product_cat", 
     'child_of' => 0, 
     'number'  => $number, 
     'orderby' => $orderby, 
     'order'  => $order, 
     'hide_empty' => $hide_empty, 
     'include' => $ids 
    ); 
    $product_categories = get_terms($args); 

    $list = array(); 
    foreach($product_categories as $cat){ 
     $thumbnail_id = get_woocommerce_term_meta($cat->term_id, 'thumbnail_id', true); 
     $image = wp_get_attachment_url($thumbnail_id); 
     $link = get_term_link($cat->term_id, 'product_cat'); 
     $list[] = array($cat->term_id, $cat->name, $image, $link);   
    } 

    return $list; 

} 

我最近說:

'child_of' => 0 

但沒有改變。

如何使其僅適用於頂級產品類別?

回答

1

爲了得到它的工作原理,缺少的參數就是'parent' => 0(但不是'child_of'

所以,你的工作代碼應該是這樣的(並將正確返回您的陣列:

function getProductCategoriesList() { 

    // since wordpress 4.5.0 
    $product_categories = get_terms($args = array(
     'taxonomy' => "product_cat", 
     'hide_empty' => false, 
     'parent'  => 0, 
    )); 

    $list = array(); 

    foreach($product_categories as $cat){ 
     $thumbnail_id = get_woocommerce_term_meta($cat->term_id, 'thumbnail_id', true); 
     $image = wp_get_attachment_url($thumbnail_id); 
     $link = get_term_link($cat->term_id, 'product_cat'); 
     $list[] = array($cat->term_id, $cat->name, $image, $link);   
    } 

    return $list; 
} 

代碼會出現在您活動的子主題(或主題)的function.php文件中,或者也存在於任何插件文件中。

經測試和工程

0

我希望這會幫助你。

解決方案:

global $post; 
$prod_terms = get_the_terms($post->ID, 'product_cat'); 
foreach ($prod_terms as $prod_term) { 

    // gets product cat id 
    $product_cat_id = $prod_term->term_id; 

    // gets an array of all parent category levels 
    $product_parent_categories_all_hierachy = get_ancestors($product_cat_id, 'product_cat'); 



    // This cuts the array and extracts the last set in the array 
    $last_parent_cat = array_slice($product_parent_categories_all_hierachy, -1, 1, true); 
    foreach($last_parent_cat as $last_parent_cat_value){ 
     // $last_parent_cat_value is the id of the most top level category, can be use whichever one like 
     echo '<strong>' . $last_parent_cat_value . '</strong>'; 
    } 

} 
相關問題