簡體   English   中英

獲取WooCommerce中頂級產品類別的自定義數組

[英]Get a custom array of the top level products categories in WooCommerce

有什么方法可以在woocomerce中獲取頂級產品類別的列表,以在我主題的自定義部分中顯示它們

這是我使用的代碼,但是它返回所有類別:

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 

但是沒有變化。

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

為了使它起作用,缺少的參數只是'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文件中,或者在任何插件文件中。

經過測試和工作

暫無
暫無

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

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