Wordpress including Custom Posts in Taxonomy Archives

Hooks and sample code to get your custom posts listed in taxonomy listings.

WordPress Logo

By default the archive loop for custom taxonomies in WordPress only queries pages and posts. And the chances are that if you have defined a custom taxonomy you also have custom post-types. Here are a couple of hooks that allow some pretty nice customisations of this previous limitation.

This code needs to go in your functions.php file, or in a plugin. The XXXX is the identifying name of the particular taxonomy which you would like to adjust.

add_filter('XXXX_taxonomy_query_posttypes', 'XXXX_taxonomy_query_posttypes');
function XXXX_taxonomy_query_posttypes($ptypes)
{
	// example usage
	unset($ptypes['post']);			// this removes the default post-type 'post' from appearing in the taxonomy listing
	$ptypes['case_study'] = 'case_study';   // this includes our custom-post-type 'case_study' in the taxonomy listing
	return $ptypes;
}

add_action( 'pre_get_posts', 'filterable_post_types_to_tax_query' );
function filterable_post_types_to_tax_query( $query ) {
	if ( is_tax() && $query->is_main_query() && !is_admin())
	{
		$current_term = get_queried_object();
		$post_types = array('page'=>'page', 'post'=>'post');
		$post_types = apply_filters($current_term->taxonomy.'_taxonomy_query_posttypes', $post_types);
		$query->set( 'post_type', array_keys($post_types) );		
	}
	return $query;
}
Published on: 12th April 2013
Categorised in: code
Tagged with: php, wordpress

leave a reply

Your email is never published nor shared. Required fields are marked *

*

*