I'm looking to display only the top level categories from a custom post type taxonomy I've created... product-category.

I'm hoping to pull the following data into a loop:

  • Category title (the_title())
  • Category description (the_archive_description())
  • Permalink (the_permalink())
  • Thumbnail (custom field... the_field(category_thumbnail))

Could somebody point me in the right direction please.

Here's my loop:

                $loop = new WP_Query();
                while ( $loop->have_posts() ) : $loop->the_post();
                    $myterms = get_terms( array( 'taxonomy' => 'taxonomy_name', 'parent' => 0 ) );
                    foreach( wp_get_post_terms() as $term ) { ?>
                        <div class="col-eq-height col-md-6" style="margin-bottom:30px;">
                            <div class="product">
                                <div id="thumbnail">
                                    <?php the_field('product_category_thumbnail'); ?>
                                <div id="content">
                                    <p id="title"><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></p>
                    <?php }
                endwhile; ?>

I believe this has already been answered perfectly in How can I get only parent terms?.

The solution is to set 'parent' => 0 when querying terms with get_terms() or WP_Term_Query. The example from that question looked like this:

$myterms = get_terms( array( 'taxonomy' => 'taxonomy_name', 'parent' => 0 ) );

You can easily loop over the result and in it retrieve the fields you mentioned.

Hope that helps! If you need more guidance, please let me know and I can look into expanding my answer a bit.

| improve this answer | |
  • Where would I exactly add the $myterms to the loop? Please see the code snippet I added to my answer. – Jake Punton Jan 17 '18 at 16:51
  • Hmm maybe I misunderstood you. Your code loops through custom posts of the "products" type. Now you want to show all the categories of a product (the "product-category" taxonomy) inside that loop, but only the parent ones? – swissspidy Jan 17 '18 at 16:57
  • Yes, only showing the top level (parent) categories. And then just that category information. When I refer to category, I mean the custom taxonomy created for my Products CPT. – Jake Punton Jan 17 '18 at 17:01
  • any ideas mate? – Jake Punton Jan 17 '18 at 17:27
  • Have you tried using wp_get_post_terms( get_the_ID(), 'product-category', array( 'parent' => 0 ) );? – swissspidy Jan 17 '18 at 20:59

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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