posts_per_page is not working on my end

The question:

I have these lines of codes, for some reason, posts_per_page is not working.

<?php
        $posts_list = get_posts(
            array(
                'posts_per_page'    => 6,
                'post_type'         => 'post',
                'post_status'       => 'publish',
                'paged'             => $i_paged
            )
        );

        $the_query = new WP_Query( $posts_list );

        // The Loop
        if ( $the_query->have_posts() ) {
            while ( $the_query->have_posts() ) {

                global $post;

                $the_query->the_post();

                $post_id = get_the_id();

                // Get fields
                $image      = get_the_post_thumbnail();
                $title      = get_the_title();
                $subtitle   = get_the_date();
                $content    = get_the_excerpt();
                $link       = get_permalink();

                $args['cards'][] = array(
                    'image'         => $image,
                    'title'         => $title,
                    'subtitle'      => $subtitle,
                    'content'       => $content,
                    'link'          => $link,
                );

                ?>

            <?php }

        } else {
            // no posts found
        }

        echo '<div class="posts-grid">';
                get_template_part( '/blocks/testimonial/testimonial-template', null, $args );
        echo '</div>';

        /* Restore original Post Data */
        wp_reset_postdata();
        ?>

The Solutions:

Below are the methods you can try. The first solution is probably the best. Try others if the first one doesn’t work. Senior developers aren’t just copying/pasting – they read the methods carefully & apply them wisely to each case.

Method 1

It’s not working because the $posts_list variable is assigned the return value of get_posts() (i.e. $posts_list = get_posts( ... )), hence $posts_list is not actually an array of arguments, but instead, it’s either an array of posts or an empty array.

So to fix the problem, define the $posts_list like so:

$posts_list = array(
    'posts_per_page' => 6,
    'post_type'      => 'post',
    'post_status'    => 'publish',
    'paged'          => $i_paged
);


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Comment