Question

I'm using Jetpack's infinite scroll function on the homepage and I only want to display posts from the category with ID 1. The problem is that my query works correctly only on the first page. On the other pages it displays posts from all categories.

Here you have my code

<?php $paged = (get_query_var('paged')) ? get_query_var('paged') : 1; ?>
<?php query_posts($query_string.'&cat=1&posts_per_page=12&paged='.$paged);?>
<?php if (have_posts()) : while (have_posts()) : the_post(); ?>
<?php get_template_part( 'content' ); ?>
<?php endwhile; endif; ?>

Do you know what's wrong with this? I'm using this code on multiple websites, but I don't have the infinite scroll there.

Was it helpful?

Solution

As @Pieter Goosen said, you shouldn't be using query_posts, nor running your own query. Instead, override the main query that already runs:

function wpse_144974_pre_get_posts( $wp_query ) {
    if ( ! is_admin() && $wp_query->is_main_query() && is_home() )
        $wp_query->set( 'cat', 1 );
}

add_action( 'pre_get_posts', 'wpse_144974_pre_get_posts' );
Licensed under: CC-BY-SA with attribution
Not affiliated with wordpress.stackexchange
scroll top