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; ?> |
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!
Worked a treat for standard posts too by changing post_type to 'post', thanks
Excellent
Just perfect! Thanks!
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Extremely helpful and exactly what I was looking for. Thank you!