簡體   English   中英

如何在Wordpress中找到帶有子類別等的產品類別?

[英]How to find the product categories with subcategories and so on in wordpress?

在這里,我得到產品的2級類別,但我想要的不止2個,例如prodA-> proda1-> proda11

$taxonomy = 'product_cat';
$all_categories = get_categories(array( "taxonomy" =>"product_cat","parent" => 0)); 
echo "<pre>"; 
print_r($all_categories); 
die();
foreach ($all_categories as $cat) {
   echo $category_id = $cat->term_id;       
   echo "parent name ==". $cat->name;
   $sub = get_categories(array("taxonomy" => "product_cat", "parent" => $category_id));
   echo "<pre>"; print_r($sub);
}

請使用此代碼,因為如果您未添加hide_empty => 0則下拉列表中不會顯示某些未附加的類別產品。

$args = array(
    'type'                     => 'product',
    'child_of'                 => 0,
    'parent'                   => '',
    'orderby'                  => 'term_group',
    'hide_empty'               => false,
    'hierarchical'             => 1,
    'exclude'                  => '',
    'include'                  => '',
    'number'                   => '',
    'taxonomy'                 => 'product_cat',
    'pad_counts'               => false
);

$cats = get_categories( $args );

根據您的要求,其他參數不是必需的。

要遍歷類別和子類別,您可以通過以下方式使用多個embed foreach循環:

$taxonomy     = 'product_cat';
$categories = get_categories( array(
    'taxonomy'  => $taxonomy,
    'orderby'      => 'name',
    'empty'        => 0,
    'parent'    => 0,
) );
echo "<div>";
foreach ($categories as $category) {
    echo '<a href="' . get_term_link( $category->slug, 'product_cat' ) . '">' . $category->name . ' (' . $category->term_id . ')</a><br>';

    $subcategories = get_categories( array(
        'taxonomy'  => $taxonomy,
        'orderby'      => 'name',
        'empty'        => 0,
        'parent'    => $category->term_id,
    ) );

    foreach ($subcategories as $subcategory) {
        echo ' — <a href="' . get_term_link( $subcategory->slug, 'product_cat' ) . '">' . $subcategory->name . ' (' . $subcategory->term_id . ')</a><br>';

        $subsubcats = get_categories( array(
            "taxonomy"  => $taxonomy,
            'orderby'      => 'name',
            'empty'        => 0,
            'parent'    => $subcategory->term_id,
        ) );

        foreach ($subsubcats as $subsubcat)
            echo ' — — <a href="' . get_term_link( $subsubcat->slug, 'product_cat' ) . '">' . $subsubcat->name . ' (' . $subsubcat->term_id . ')</a><br>';
    }
}
echo "</div>";

要使子類別的級別超過2級,則需要為每個附加級別嵌入一個附加的foreach循環…

此代碼已經過測試並且可以工作。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM