Modifying loop on a custom page, strange behaviour

I want to setup a custom page on my site that pulls in posts from only one category. I’ve taken my main blog page template, duplicated the file and assigned it as a template to my new page. I’ve then ran a function on the filer ‘pre_get_posts’ to modify the query for that page.

    function include_category($query)
    {
        if(is_page(16080) && $query->is_main_query())
        {
            $query->set('cat', '2508');
        }
    }
    add_action('pre_get_posts', 'include_category');

However, this has no impact.. the page is only showing one ‘post’ which is linked to the page I am on. ie.. the page is called ‘/custom-posts’ .. the one ‘post’ that appears where the loop should be is linked to ‘/custom-posts’.

I am not doing anything out of the ordinary with the loop:

        <?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>

            <?php if ( has_post_thumbnail() ) : ?>
            <?php endif; ?>

            <?php the_title(); ?>
            <?php the_permalink(); ?>

        <?php endwhile; else : ?>
            <p><?php _e( 'Sorry, no posts matched your criteria.' ); ?></p>
        <?php endif; ?>

Why would this return a page?

Thanks

1 Answer
1

pre_get_posts does not work as expected on true pages and static front pages. You should create a custom query using WP_Query to return the posts that you need.

EDIT

Thanks to @birgire in comments, here is an interesting approach using pre_get_posts with a static front page

Leave a Comment