2017-08-17 3 views
1

のトップレベルの製品カテゴリのカスタム配列であるになってしまうが、ここに私のテーマの中にカスタムセクションに</p> <p>それらを表示するためにwoocomerceでトップレベルの製品カテゴリの一覧を取得するがどのような方法は、私が使用するコードWooCommerce

'child_of' => 0 

をしかし、変更はありません。私は最近追加した

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; 

} 

:それはすべてのカテゴリを返します。

トップレベル製品カテゴリのみで動作させる方法を教えてください。

答えて

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

} 
関連する問題

 関連する問題