For my homepage I want to display posts for a specific category (for example category “food”) instead of the default display of all posts.
How can this be accomplished? Is it true that I am supposed to use wp_query()
and avoid query_posts()
?
Also, will I need to reset with wp_reset_postdata();
for this loop in index.php
?
I have read codex and googled around, but still am not confident with altering the Loop.
I thought the code below would work but I get White Screen of death in WordPress Themes 2012 and 2013. I replaced the code in index.php
with
<?php
$query = new WP_Query('cat=1');
if ($query->have_posts()) :
while ($query->have_posts()) : $query->the_post();
the_title();
endwhile;
endif;
?>
Edit:
White Screen of Death was due to a missing ?>
elsewhere in my index.php
file. Noob mistake. But now I am having issues with pagination. Page 2 displays the same posts as page 1. What could be wrong?
My code for pagination inside functions.php
if ( ! function_exists( 'my_pagination' ) ) :
function my_pagination() {
global $wp_query;
$big = 999999999; // need an unlikely integer
echo paginate_links( array(
'base' => str_replace( $big, '%#%', esc_url( get_pagenum_link( $big ) ) ),
'format' => '?paged=%#%',
'current' => max( 1, get_query_var('paged') ),
'prev_next' => True,
'total' => $wp_query->max_num_pages
) );
}
.
.
Edit:
I used Pieter Goosen’s solution below. Problems fixed.
You should not change the main query for a custom query on the home page or any archive page. Custom queries is meant for secondary content, not to display your main content. I have done a very detailed post on this matter on WPSE which you can check out here. It also covers a bit why you should never use
query_posts
.To solve your problem, delete your custom query from your index.php, and just add the default loop back like
You will now again see all posts on your home page. To only show the selected category on your homepage, use
pre_get_post
to alter the main query before it is executed. Add this to your functions.phpThis will sort out your pagination problem as well
EDIT
For the sake of SO users, I have reposted my answer from WPSE to this question by same OP