Support » Developing with WordPress » Fetching post content from all top-level terms in a custom taxonomy

  • Resolved ikarus7


    Hi guys,

    I’ve been trying to figure this one out for a while, scouring the internet for solutions but to no avail. Wondering if you guys could lend a hand 🙂

    I’ve created a custom post type products, with a custom taxonomy of product_type.

    What I’m trying to do is create a post query that will fetch all top level terms (in alpabetical order) in the product_type taxonomy and output the first x number of posts for 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

    The first hurdle is fetching only top-level taxonomy terms into an array, which I can then feed into a query.

    I’ve been playing around with get_categories():

    $cat_args = array(
    	'taxonomy' => 'product_type',
    	'type' => 'products',
    	'orderby' => 'name'
    $categories = get_categories('taxonomy=product_type&type=products');

    to feed into WP_query but unfortunately get_categories() doesn’t support the ‘depth’ parameter as available with wp_list_categories().

    Am I going about this the right way?

Viewing 2 replies - 1 through 2 (of 2 total)
  • I would recommend using 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...

    I hope that helps. You can read more about get_terms() here:

    Thanks ChaseWiseman, that works well!

    What I’ve done is slotted this query inside the foreach( $types as $type ) loop:

    $query_args = array(
    	'orderby' => 'title',
    	'order' => 'ASC',
    	'post_type' => 'products',
    	'posts_per_page' => 4,
    	'tax_query' => array(
    		// query the product_type using the current type's slug and only fetch parent items
    			'taxonomy' => 'product_type',
    			'field' => 'slug',
    			'terms' => $type->slug,
    			'include_children' => false
    $type_query = new WP_Query( $query_args );

    That fetches my required posts and I can then extract data from each post from there. This does exactly what I need it to do. Thanks again!

Viewing 2 replies - 1 through 2 (of 2 total)
  • The topic ‘Fetching post content from all top-level terms in a custom taxonomy’ is closed to new replies.