How to control a category in the Wordpress loop

How to control a category in the Wordpress loop

While reading though some twitter updates this morning, I stumbled across one that was asking if anyone knew a way to exclude a specific category in Wordpress from the loop, unless it was certian page template. After a quick minute of thinking, I came up with this small function that will do just that.

Place in your functions.php file
if( !is_page_template('user-feed.php') ){ // Replace 'user-feed.php' with your page template file name
	global $wp_query;

	$cat = get_cat_ID('user_feed'); // Replace 'user_feed' with your desired category to exclude from the regular loop

	$wp_query->query_vars['cat'] = '-'.$cat;
}

How this works is that first it checks to see if the page or post we're viewing is NOT USING the page template that we want to category to appear in, and if it's not, adjusts the query_vars to exclude that category from the loop.

If the page the user is viewing IS USING the page template, then the query_vars are left unchanged and that category's posts are displayed in the loop.

Share the Love Share the Love

Add to Reddit Add to StumbleUpon Add to Mixx Add to Delicious Add to designfloat

About the author: Fire G

Hey, I'm the founder of Fire Studios, and thus, have my hands in everything that goes on here at FS. I manage the content, moderate the comments, design everything, code everything, provides a lot of articles, host the official podcast FS-Air, and run/manage most of the other sites in the FI family. Often times I'll come to be working on so many things that I hardly accomplish much, but that's what makes me who I am.

2 Reader Comments

  •  
  • Andrew Turner
    July 7th

    Thanks for posting that! I finally figured out a different solution after a few days, It's a little different to this one, but works much the same.

  • Flex Developer
    July 31st

    very nice article…keep on the good work

Leave a Reply