Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aronmoshe-m/a95ad3dbc2b95f60548f2d879cdc2fc7 to your computer and use it in GitHub Desktop.
Save aronmoshe-m/a95ad3dbc2b95f60548f2d879cdc2fc7 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 = 'custom_post_name_here';
// 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; ?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment