Posts loop with pagination on a single post page

Today, I need your help.

On my pages I have a sidebar with :

        <div class="sidebarActu">
            <ul>
            <?php
            $i = 1;
            while ( have_posts() ) : the_post();?>
                <li <?php if($i == 1){?>class="selected"<?php } ?> > <?php get_template_part( 'template-parts/content1', get_post_format() );?> </li> <?php
            $i++;
            endwhile; ?>
            <li class="all"><?php echo previous_posts_link();?> | <?php echo next_posts_link(); ?></li>
            </ul>
        </div>

This works perfectly !

Now, on my single.php, this not works because have_posts() returns 1 …

So I tried something :

        <div class="sidebarActu">
            <ul>
            <?php
            $i = 0;
            $posts = get_posts();
            foreach($posts as $post){
                $pid = $post->ID;
                $date = $post->post_date;
                $date = date_create($date);
                $date = date_format($date, 'd/m/y');
                ?>

                <li <?php if($id == $pid){?>class="selected"<?php } ?> ><h2 class="entry-title"><a href="https://wordpress.stackexchange.com/questions/267672/<?php get_site_url(); echo $post->post_name; ?>"><?php echo $post->post_title; ?></a></h2><span><?php echo $date; ?></span></li>
                <?php
                if (++$i == 4) break;
            }
            ?>
            </ul>
        </div>

Works perfectly, but can’t have pagination. Can someone help me?

1 Answer
1

The simple answer is, get_posts does not work with pagination. In stead you should use wp_query, like this:

$args = array ('posts_per_page' => 5);
$posts = new WP_Query ($args);

Leave a Comment