WordPress displaying posts on different pages

I am creating a landing page (one page with many section) in WordPress, and I’m calling each section using get_template_part(). So I have something like this;

    <?php get_template_part( 'content', 'reasons-to-purchase'); ?>   
    <?php get_template_part( 'content', 'testimonials'); ?>  
    <?php get_template_part( 'content', 'reasons-to-purchase'); ?>   

Each content file then has a loop to return the posts that match its category, with posts_per_page set to one, as shown below (content-reasons-to-purchase.php);

Read More
            <?php

        $args = array(
            'post_type' => 'section',    
            'category_name' => 'Reasons-To-Purchase',
            'posts_per_page' => 1,
            'orderby' => 'date',
            'order' => 'DESC'
        );

        $the_query = new WP_Query ( $args );

 if (get_category_by_slug('Reasons-To-Purchase')->category_count > 0 ) {?>


<!-- Featured content image or slider. -->
        <div class="container panel">

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

           <?php the_content(); ?>


        </div>

<?php } ?>

            <?php wp_reset_query(); ?> <div class="clearfix"></div>    

What I would like to is create as many as these sections in which ever order I like and the loop within each section pulls the next post assigned to that category. So for example in the first ‘reasons-to-purchase’ section the first post is pulled and then in the second ‘reasons-to-purchase’ the second post is called. At the moment I reset the loop in each file using ‘wp_reset_query()’ so it doesn’t interfere with the next section which may be different. Basically the loop has to continue for the next similar named section without duplicating any posts..

Any ideas on how to do this or advice would be most appreciated.

Related posts

Leave a Reply

1 comment

  1. You need to pass page parameter before calling get_template_part() but get_template_part() does not support the re-use of your variables, you need to use locate_template() and include()

    $page=1;
    include(locate_template('content-reasons-to-purchase.php'));
    include(locate_template('content-testimonials.php'));
    $page=2;
    include(locate_template('content-reasons-to-purchase.php'));
    $page=3;
    include(locate_template('content-reasons-to-purchase.php'));/* and so on page 4,5,6... */
    

    In you template make a slight change of code

    if(empty($page)){
    $page=1;
    }
    
     $args = array(
                'post_type' => 'section',    
                'category_name' => 'Reasons-To-Purchase',
                'posts_per_page' => 1,
                'orderby' => 'date',
                'paged'=>$page, /* <======= get page no from your file i.e locate_template(...) and use here*/
                'order' => 'DESC'
            );
    

    Hope it makes sense