WordPress noodling: displaying date-based archives from only one category
I have a client who’s using the Posts functions in Wordpress for multiple purposes. One issue we’ve run up against is that we want the date-based archives (i.e., in the sidebar, showing the months of posts) to only pull from one category out of the 30-40 categories that they have. I was using wp_get_archives, but it doesn’t have a category parameter as I’d hoped.
After some futzing around, I found a combo of two solutions that worked. Here’s the code I dropped into my theme’s functions.php; then I used wp_get_archives in another function to create a widget for the sidebar (not included below). Enjoy!
## First, on monthly archives, only display posts from the category with an ID of 109
function exclude_stuff($query) {
if ( $query->is_month) {
$query->set(‘cat’, ‘109’);
}
return $query;
}
add_filter(‘pre_get_posts’, ‘exclude_stuff’);
## Then, when wp_get_archives is used to display monthly archives, only show months with posts from the category with an ID of 109
add_filter( ‘getarchives_where’, ‘customarchives_where’ );
add_filter( ‘getarchives_join’, ‘customarchives_join’ );
function customarchives_join( $x ) {
global $wpdb;
return $x . ” INNER JOIN $wpdb->term_relationships ON ($wpdb->posts.ID = $wpdb->term_relationships.object_id) INNER JOIN $wpdb->term_taxonomy ON ($wpdb->term_relationships.term_taxonomy_id = $wpdb->term_taxonomy.term_taxonomy_id)”;
}
function customarchives_where( $x ) {
global $wpdb;
$includes= ‘109’; // category id to include
return $x . ” AND $wpdb->term_taxonomy.taxonomy = ‘category’ AND $wpdb->term_taxonomy.term_id = ‘$includes’”;
}
