Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

WordPress

WP get posts with custom post format from every category

I'm trying to get posts from all categories but with one post format, the post format named homePost, i just a beginner in WordPress and i just finished learning the front-end developing and PHP+MySQL developing and i need your help guys :) Here is my code

 <?php $args = array( 'orderby' => 'name', 'parent' => 0 );
 $categories = get_categories( $args );
 foreach ( $categories as $category ) {
 $homePosts = array(
 'post_type'=> 'post',
 'post_status' => 'publish',
 'category'         => $category->cat_ID,
 'order' => 'DESC',
 'tax_query' => array(
 array(
'taxonomy' => 'post_format',
'field' => 'slug',
'terms' => array( 'homePost' )
)
)
 );
 $asides = get_posts( $homePosts );
 if ( count($asides) ) {
 foreach ( $asides as $homePosts ) {
        '<p>' + 'Test' + '</p>' ;
    }
}
 }
 ?>

Since you want all categories to be displayed, you can try removing the category terms from your array. :)

1 Answer

Mike Mazzolini
Mike Mazzolini
3,677 Points

Zaid,

You have many ideas smashed together in this code chunk. What is happening is that you are too specific in your post query parameters so you are trying to regain functionality that is there by default. For example, you don't need to specify a category id if you want all the categories and you don't need to specify desc order.

If homePost is a custom taxonomy then use this code:

$args = array (
'post_type' => 'post', // this line is only needed if you have custom post types, if not, you can remove this line
'post_status' => 'publish',
'tax_query' => array(
    array(
        'taxonomy' => 'post_format',
        'field'    => 'slug',
        'terms'    => 'homePost'
        )
    )
);

If homePost is a custom post type then use this code:

$args = array (
'post_type' => 'homePost',
'post_status' => 'publish'
);

Both $args arrays will return all categories in desc order. After you pick one then do the query:

$query = new WP_Query( $args );

Now iterate through each post returned from the query:

if (count($query->posts) > 0)
{
// each post code, like container div
}
else
{
echo "no posts";
}
Mike Mazzolini
Mike Mazzolini
3,677 Points

sorry my line breaks disappeared for some reason