简体   繁体   中英

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

Is there any way to get list of top level products categories in woocomerce to display them in custom section within my theme

Here is the code I use, but it returns all categories:

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;

}

I have added recently:

'child_of'   => 0 

But there is no change.

How to make it work for only top level product categories?

To get it works, the missing argument is just 'parent' => 0 (but not 'child_of' )

So your working code should be something like this (and will return your array correctly:

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

Code goes in function.php file of your active child theme (or theme) or also in any plugin file.

Tested and works

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM