WordPress.org

Ready to get started?Download WordPress

Forums

[resolved] Fetching post content from all top-level terms in a custom taxonomy (3 posts)

  1. ikarus7
    Member
    Posted 2 years ago #

    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
    etc...

    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?

  2. Chase Wiseman
    Member
    Posted 2 years ago #

    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...
        endforeach;
    endif;

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

  3. ikarus7
    Member
    Posted 2 years ago #

    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
    		array(
    			'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!

Topic Closed

This topic has been closed to new replies.

About this Topic