Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
WordPress: Loop through Categories and Display Posts Within
<?php
/*
* Loop through Categories and Display Posts within
*/
$post_type = 'features';
// Get all the taxonomies for this post type
$taxonomies = get_object_taxonomies( array( 'post_type' => $post_type ) );
foreach( $taxonomies as $taxonomy ) :
// Gets every "category" (term) in this taxonomy to get the respective posts
$terms = get_terms( $taxonomy );
foreach( $terms as $term ) : ?>
<?php
$args = array(
'post_type' => $post_type,
'posts_per_page' => -1, //show all posts
'tax_query' => array(
array(
'taxonomy' => $taxonomy,
'field' => 'slug',
'terms' => $term->slug,
)
)
);
$posts = new WP_Query($args);
if( $posts->have_posts() ): ?>
<?php echo $term->name; ?>
<?php while( $posts->have_posts() ) : $posts->the_post(); ?>
<?php if(has_post_thumbnail()) { ?>
<?php the_post_thumbnail(); ?>
<?php }
/* no post image so show a default img */
else { ?>
<img src="<?php bloginfo('template_url'); ?>/assets/img/default-img.png" alt="<?php echo get_the_title(); ?>" title="<?php echo get_the_title(); ?>" width="110" height="110" />
<?php } ?>
<?php echo get_the_title(); ?>
<?php the_excerpt(); ?>
<?php endwhile; endif; ?>
<?php endforeach;
endforeach; ?>
@fciotola

This comment has been minimized.

Copy link

@fciotola fciotola commented Aug 23, 2017

hi DevinWalker i use this good code, how can i exclude some category from this loop?

@glendonray

This comment has been minimized.

Copy link

@glendonray glendonray commented Jan 23, 2018

Thank you for sharing! This worked perfect!

@rzfreitas

This comment has been minimized.

Copy link

@rzfreitas rzfreitas commented Jul 5, 2018

Works like a charm! Thanks man! Save my day.

@tobiasger

This comment has been minimized.

Copy link

@tobiasger tobiasger commented Aug 31, 2018

I get Cannot use object of type WP_Query when using the $posts variable in the if/while loop. So I simply changed the variable to $query or whatever in order for it to work without an error.

@aronmoshe-m

This comment has been minimized.

Copy link

@aronmoshe-m aronmoshe-m commented Nov 15, 2018

Extremely helpful and exactly what I was looking for. Thank you!

@krishna-wac

This comment has been minimized.

Copy link

@krishna-wac krishna-wac commented Apr 4, 2019

Exactly what I was looking for. I just copied and paste and change with my custom post type name. It's working excellent. Thank you!

@fcswebsites

This comment has been minimized.

Copy link

@fcswebsites fcswebsites commented Apr 26, 2019

Worked a treat for standard posts too by changing post_type to 'post', thanks

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment