Skip to content

Instantly share code, notes, and snippets.

@DevinWalker
Created April 17, 2015 17:31
Show Gist options
  • Star 29 You must be signed in to star a gist
  • Fork 10 You must be signed in to fork a gist
  • Save DevinWalker/6fb2783c05b46a2ba251 to your computer and use it in GitHub Desktop.
Save DevinWalker/6fb2783c05b46a2ba251 to your computer and use it in GitHub Desktop.
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
Copy link

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

@glendonray
Copy link

Thank you for sharing! This worked perfect!

@rzfreitas
Copy link

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

@tobiasger
Copy link

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
Copy link

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

@krishna-wac
Copy link

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
Copy link

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

@saeed51100
Copy link

Excellent

@emestrom
Copy link

Just perfect! Thanks!

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