David Nash

Wordpress Guru Sydney

WordPress: Limit Archives to Single Category

Posted on December 3, 2011

Late yesterday afternoon a client asked if I could look at a business’s WordPress installation. They had posts in several categories but only wanted to show the “Latest News” posts in the archives.

WordPress is designed around blog posts, whereas I find that many business or company sites are designed around pages (eg About Us, Contact Us) – and don’t use WordPress’ powerful blogging tools on the front page. My site is an example – the content on the home page doesn’t change that much.

This means that many of the solutions are also geared around blog-post design.

While searching I found a few examples of how to exclude a specific category from the archives, when what I needed was to include only one category in the WordPress archives – generated in the theme by wp_get_archives().

The solution is to add a filter that modifies the SQL used by wp_get_achives() to the theme’s function.php:

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;
$include = '1'; // category id to include
return $x . " AND $wpdb->term_taxonomy.taxonomy = 'category' AND $wpdb->term_taxonomy.term_id IN ($include)";
}

Replace ’1′ with the category ID (wp-admin > posts > categories > edit, then in the address bar it is directly after ‘&tag_ID’) and that’s it. wp_get_archives() will now only display posts from that category.

I found this in http://wordpress.org/support/topic/wp_get_archives-and-conditional-tags?replies=6#post-1578041 (thanks Paul!).

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>