I stumbled across this solution a few months ago as I was playing around with a concept idea in WordPress from wesbos. (List WordPress Posts by Category) As I’ve started working on my latest project, I needed to re-visit the idea. The problem was that I also wanted to limit it to posts within a certain time range and use it for a “sidebar”. I could have spent some time searching for a plugin that would accomplish that, but why bother? On this project, it would be on one page only, so I could hard-code it in.
Wes uses the standard “query_posts” method of running the loop, because he’s not really changing anything or making any significant queries. I assume that it would be the same across the board for probably 90% of the folks out there trying it. The Codex these days suggests that if you’re going to modify the loop (or run a separate loop outside the main loop), you use WP_Query.
So in order to modify Wes’ original example as well as add in my own changes, I pretty much wound up re-writing a lot of the example. Just throw this in whatever DOM element you want (div, aside, etc.)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
<?php $cats = get_categories(); function filter_where( $where = '' ) { // posts in the last x days $where .= " AND post_date > '" . date('Y-m-d', strtotime('-365 days')) . "'"; return $where; } foreach ($cats as $cat) { $cat_id= $cat->term_id; echo "<h4 class='news-category'>".$cat->name."</h4><ul>"; $query_string = array( 'post_type' => 'post', 'post_status' => 'publish', 'cat' => $cat_id ); add_filter( 'posts_where', 'filter_where' ); $query = new WP_Query( $query_string ); remove_filter( 'posts_where', 'filter_where' ); if ( $query->have_posts()) : while ( $query->have_posts()) : $query->the_post(); ?> <li><a href="<?php the_permalink();?>"><?php the_title(); ?></a> <?php echo get_the_date();?></li> <?php endwhile; echo "</ul>"; endif; } wp_reset_postdata(); ?> |
Still needs some cleanup, and I want to move some of that into the core functions of the theme so I’m only calling a function or two. (To be honest, the whole theme at this point lacks a fair amount of structure or sensibility to the code.)
But it’s still a pretty good start.