Assuming it is a page template that is not set to Blog Posts Page
:
Using pre_get_posts
to show only one category doesn’t work as the main query contains only page content and is not a post loop. So we can do this using a secondary query using WP_Query
.
Look at WP_Query
category parameters
<?php
$args = new WP_Query( array( 'cat' => "YOUR CATEGORY ID" ) );
$the_query = new WP_Query( $args );
// The Loop
if ( $the_query->have_posts() ) {
while ( $the_query->have_posts() ) {
$the_query->the_post();
the_content();
}
/* Restore original Post Data */
wp_reset_postdata();
} else {
// no posts found
}
If the page is set to Posts Page
then we can use pre_get_posts
(in functions.php
)
function home_category( $query ) {
if ( $query->is_home() && $query->is_main_query() ) {
$query->set( 'cat', '1' ); // set req. cat id
}
}
add_action( 'pre_get_posts', 'home_category' );
Note:
As @PieterGoosen pointed:
Single pages do not need the while loop, it just need a call to the_post(). It is all you actually need. It is however always better to include the while loop part as some plugins hook into have_posts()