Brandammo

Blog

Useful WordPress Snippets, Excluding Categories from Archives, Excluding Categories from Archive Dropdown

There are times when you need to exclude posts belonging to certain categories in your custom pages or archives, after scouring the internet, i take no credit for these, but this can simply be achieved by using the following code snippets:

Exclude a category from custom pages or archive pages in wordpress:

The following applies to all date archive pages and hides posts which are listed in category 6.
(place this code into your theme’s functions.php file)

function exclude_stuff($query) {
if ( $query->is_date) {
		$query->set('cat', '-6');
}
return $query;
}
add_filter('pre_get_posts', 'exclude_stuff');

Exclude a category from the Archives Dropdown and updates count (in brackets)

The example below excludes posts in category ID 6:

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

3 thoughts on “Useful WordPress Snippets, Excluding Categories from Archives, Excluding Categories from Archive Dropdown

  1. Kathleen Palnau on said:

    The first one is a nice code, but I don’t need exactly this. I changed the ( $query->is_date) into ( $query->is_category) and thats working better for me. But now my category that I whant to hide isn’t shown on all pages. But I still want one page where it is shown. Is there a possibility to make something like that?

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>