Monday, September 1, 2014

How To: Show Posts From Only Specific Categories on Your WordPress Homepage

Sometimes you'll need to show posts from only one category on your homepage. It's easy enough to do it. Following are the steps you need to follow:

Find Your Category ID

First you will have to find the ID of the category you want to show. When you're in the admin, hover over the edit link (or the title) for any of your categories and look at the address in your status-bar (that's the bar along the bottom of your browser window if you don't know about it), you should see the category ID at the end of the URL.

You can also use a plugin called Reveal IDs for this purpose.

Insert Code

Once you have your category ID, open your functions.php file and insert the following function code: (Appearances > Editor > Theme Functions – functions.php)

function my_home( $query ) {
  if ( $query->is_home() && $query->is_main_query() ) {
     $query->set( 'cat', '5');
  }
}
add_action( 'pre_get_posts', 'my_home' );


In this example above, the category ID I have used is 5.

If you would like to include more than one category, then just add another ID by inserting a comma and the ID number. For example, this will display posts from category 5 and 6:

$query->set( 'cat', '5, 6' );

You can also use get_cat_id() function for retrieving the category, like this:

$cat_id = get_cat_id('category name');
$query->set( 'cat', $cat_id );


And that's all. You should now see posts only from this category on your homepage.

Happy coding!

0 comments:

Post a Comment