Site icon Web Niraj

Modify WordPress Archive to Display Only Certain Tags (wp_get_archives)

I recently ran into a problem where I wanted to display only posts tagged with a specific name in the WordPress Archive page (part of my theme). However, searching on Google only showed how to filter posts by Category. I did some research and found a solution to my problem.

Solution

To help others with a similar problem, I modified the examples I found to filter the Archive by tags. The solution I devised was:

function customarchives_where( $x ) {
	global $wpdb;

	$include = '163'; // tag id to include
	return $x." AND $wpdb->term_taxonomy.taxonomy = 'post_tag'
		AND $wpdb->term_taxonomy.term_id IN ($include)";
}

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)";
}

add_filter('getarchives_where','customarchives_where');
add_filter( 'getarchives_join', 'customarchives_join' );

The above code should be placed in the functions.php file in your theme. The customarchives_where function includes a comma-separated list of Tag IDs that you want to include in your archive.

When your theme calls the wp_get_archives() function, the above filters are called and the Archive Query is modified to include only the tags you want.

Modification

The above example can easily be modified to exclude tags (instead of include). Change the getarchives_where() function to:

function customarchives_where( $x ) {
	global $wpdb;

	$exclude = '163'; // tag id to include
	return $x." AND $wpdb->term_taxonomy.taxonomy = 'post_tag'
		AND $wpdb->term_taxonomy.term_id NOT IN ($exclude)";
}

Similarly, you can easily include (or exclude) a category by changing the getarchives_where() function to:

function customarchives_where( $x ) {
	global $wpdb;

	$include = '163'; // tag id to include
	return $x." AND $wpdb->term_taxonomy.taxonomy = 'category'
		AND $wpdb->term_taxonomy.term_id IN ($include)";
}
Exit mobile version