Fetching post content from all top-level terms in a custom taxonomy

Problem: User has been trying to figure this out for a while, searching the internet for solutions but not helpful. User has created a custom post type products, with a custom taxonomy of product_type.

What He is trying to do is create a query that will fetch all top level posts (in alphabetical order) in the product_type taxonomy and output the first n number of posts related to each taxonomy term. Example:

product_type A
– Post 1
– Post 2

product_type B
– Post 1
– Post 2

product_type C
– Post 1
– Post 2

He has been playing around with get_categories():
$cat_args = array(
'taxonomy' => 'product_type',
'type' => 'products',
'orderby' => 'name'
);

$categories = get_categories('taxonomy=product_type&type=products');
I have use this WP_query but unfortunately get_categories() doesn’t support the ‘depth’ parameter as available with wp_list_categories().

Solution :
Use the get_terms() function for this. Setting the ‘parent’ arg to 0 should cause it to return only top-level terms. Here’s what you will want to do:
$types = get_terms( 'product_type', array(
'parent' => 0
) );

// Any types?
if ( $types ) :
// Now start the loop.
foreach ( $types as $type ) :
// Do your WP_Query stuff here...
endforeach;
endif;

I hope that helps. You can read more about get_terms() here: http://codex.wordpress.org/Function_Reference/get_terms.

Conclusion:
Every problem has a solution. Above i have stated the solution of your problem. Programming can be fun, so can cryptography however they should not be combined. Keep practicing coding. Don’t bother about problems.

Leave a Reply

Your email address will not be published. Required fields are marked *