2

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

3

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

  • 1
    I remember scratching my head over a failing is_front_page() check within pre_get_posts here ;-) – birgire Nov 19 '15 at 11:54
  • Thanks for this @birgire For some strange reason I cannot post comments from my mobile anymore, seems like a bug that came with the new design – Pieter Goosen Nov 19 '15 at 16:31
  • let's hope that's a bug and not a new feature ;-) – birgire Nov 19 '15 at 16:46

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.