I am using woo commerce theme for my site. I am trying to display a list of main product category list. I tried this code. But it returns all the main and sub categories.

$product_category = wp_get_post_terms( $post->ID, 'product_cat' );

I need to display just the main product category list. How to do that?

4 Answers 4


Check the parent of each category, top-level terms will have a parent value of 0:

$product_category = wp_get_post_terms( $post->ID, 'product_cat' );

foreach( $product_category as $cat ):
    if( 0 == $cat->parent )
        echo $cat->name;

You can very easily do so using woocommerce shortcodes

echo do_shortcode('[product_categories number="12" columns="4"]');

if you want the shorcode to show all categories do so:

echo do_shortcode('[product_categories number="12" columns="4" parent="0"]');

I believe I have made it clear enough for you to understand.

You can also take a look at how it's done in content_product-cat.php and use your own custom loop, the shortcodes above will output the content of this file btw.


Please use this code.

It's working for me..

$term = get_queried_object()->term_id;
$termid = get_term($term, 'product_cat' );

        $args = array(
            'orderby'       => 'name', 
            'order'         => 'ASC',
            'hide_empty'    => false, 
            'child_of'      => $term, 
            'parent'        =>0
    $subproducts = get_terms( 'product_cat', $args);
    foreach ($subproducts as $subproduct) { 
    echo $subproduct->name; ?>
  • 1
    Please don't just dump code, perhaps edit and add some explanation how this might solve the problem. Commented Feb 28, 2015 at 10:59

taken from here : http://stackoverflow.com/questions/20777929/woocommerce-how-do-i-get-the-most-top-level-category-of-the-current-product-ca/#answer-20778095

function get_root_term() {

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 ) {
        $root_term = $last_parent_cat_value;
return $root_term;

// usage 
$root_term = get_root_term();

if ( $root_term === 27 ) {
// do something

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.