Display all posts from specific categories on a page

I want to display all posts from specific categories on a single page.
Therefore I edited the page.php file in my theme folder.
I added an ‘if-clause’ to check which page currently being displayed and load all posts from the following categories.

<?php get_header(); ?>

<div id="primary">
    <div id="content" role="main">

<?php
    if (is_page(26)) {
        query_posts('cat=2,6,9,13&showposts=-1&orderby=date');    
        if (have_posts()) : 
            while (have_posts()) : 
                the_post(); 
                get_template_part( 'content', 'page' );
            endwhile; 
        endif;  
    } else {
        while ( have_posts() ) : 
            the_post(); 
            get_template_part( 'content', 'page' ); 
        endwhile; // end of the loop. 
    }
?>

    </div><!-- #content -->
</div><!-- #primary -->

<?php get_footer(); ?>

But when I load my page 26 nothing will be displayed.

Related posts

Leave a Reply

2 comments

  1. I’d Advise adding the arg of the category in an array. And don’t use query_posts.
    Also showposts is deprecated use posts_per_page instead.

    $args = array (
        'cat' => array(2,6,9,13),
        'posts_per_page' => -1, //showposts is deprecated
        'orderby' => 'date' //You can specify more filters to get the data 
    );
    
    $cat_posts = new WP_query($args);
    
    if ($cat_posts->have_posts()) : while ($cat_posts->have_posts()) : $cat_posts->the_post();
            get_template_part( 'content', 'page' );
    endwhile; endif;
    
  2. This happens because you are still using query_posts(). Stop doing that. Use WP_Query instead:

    $extra_posts = new WP_Query( 'cat=2,6,9,13&showposts=-1&orderby=date' );
    if ( $extra_posts->have_posts() )
    {
        while( $extra_posts->have_posts() )
        {
            $extra_posts->the_post();
            get_template_part( 'content', 'page' );
        }
        wp_reset_postdata();
    }