Skip to content

Instantly share code, notes, and snippets.

@GaryJones
Created February 5, 2012 18:56
Show Gist options
  • Select an option

  • Save GaryJones/1747188 to your computer and use it in GitHub Desktop.

Select an option

Save GaryJones/1747188 to your computer and use it in GitHub Desktop.
Display linked categories and the posts within those categories.
<?php
remove_action( 'genesis_loop', 'genesis_do_loop' );
add_action( 'genesis_loop', 'gmj_category_listings' );
/**
* Display linked categories and the posts within those categories.
*
* @author Gary Jones
* @link https://gist.github.com/1747188
*/
function gmj_category_listings() {
// Get array of category objects, in alphabetical order
$args = array(
'orderby' => 'name',
'order' => 'ASC'
);
$categories = get_categories( $args );
// Loop through each category
foreach ( $categories as $category ) {
// Find posts in just this category OR find posts in this category or
// child categories - comment out as appropriate
$posts_query_args = array(
// 'category__in' => $category->cat_ID, // JUST this category
'cat' => $category->cat_ID, // This category or a child category
'posts_per_page' => -1, // Make all posts in a category show
);
$posts_query = new WP_Query( $posts_query_args );
if ( $posts_query->have_posts() ) {
// We have at least one post, so let's echo out the category name
printf(
'<h2><a href="%s" title="%s">%s</a></h2>',
esc_url( get_category_link( $category->term_id ) ),
esc_attr( sprintf( __( "View all posts in %s" ), $category->name ) ),
$category->name
);
echo '<ul>';
// Loop through the posts
while ( $posts_query->have_posts() ) {
$posts_query->the_post();
echo '<li><a href="' . esc_url( get_permalink() ) . '">' . get_the_title() . '</a></li>';
}
echo '</ul>';
}
}
// Now we've finished looping, reset the global $post to the data of the
// page that our template is being used on.
wp_reset_postdata();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment