How to limit Posts on Posts page to a specific Category in WordPress

Posted on

In a comment on Genesis Starter Child Theme, a user asked,

Thank you for the changes, they are great! In the Genesis > Theme Settings there is a ‘blog page template’ section that allows you to select to show only posts from a specific category. However, with the changes there is no blog page template now so how do I still show only recents posts from one category on the home page?

Thanks to this wonderful post by Bill Erickson, we know that pre_get_posts is the way to go in this situation.

Adding the following in child theme’s functions.php shows only Posts from a particular category on the Posts page (this would be the homepage by default):

add_action( 'pre_get_posts', 'sk_show_posts_from_a_category_posts_page' );
/**
 * Show Posts from a specific category on Posts page
 *
 * @author Bill Erickson
 * @author Sridhar Katakam
 * @link http://www.billerickson.net/customize-the-wordpress-query/
 * @param object $query data
 *
 */
function sk_show_posts_from_a_category_posts_page( $query ) {

	if( $query->is_main_query() && !is_admin() && is_home() ) {
		$query->set( 'category_name', 'category-1' ); // Replace "category-1" with your category slug
	}

}