Created
April 17, 2015 17:31
-
-
Save DevinWalker/6fb2783c05b46a2ba251 to your computer and use it in GitHub Desktop.
WordPress: Loop through Categories and Display Posts Within
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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; ?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Just perfect! Thanks!