Site icon Hip-Hop Website Design and Development

WordPress ignoring LIMIT / posts_per_page despite being in wp_query

Using WP query:

$myquery = new WP_Query( array(
    'posts_per_page' => $instance['count'],
    'meta_key' => 'mywp_post_views_count',
    'orderby' => 'meta_value_num',
    'order' => 'DESC'
) );

Let’s get the request:

echo $myquery->request;

It returns:

SELECT SQL_CALC_FOUND_ROWS wp_posts.ID
    FROM wp_posts
    INNER JOIN wp_postmeta
    ON ( wp_posts.ID = wp_postmeta.post_id )
    WHERE
        1=1
        AND wp_posts.post_type = 'post'
        AND ( wp_posts.post_status = 'publish' OR wp_posts.post_status = 'private )
        AND ( wp_postmeta.meta_key = 'mywp_post_views_count' )
    GROUP BY wp_posts.ID
    ORDER BY wp_postmeta.meta_value+0 DESC
    LIMIT 0, 5

This runs correctly in MySQL, giving me 5 post ID’s. But WordPress returns 120 results!

echo '$myquery = ' . count( $myquery->posts );

returns: $myquery = 120

And I’ve checked when looping through:

 while ( $myquery->have_posts() ) : $myquery->the_post();

It does output the 120 unique posts, rather than the expected 5 posts.

I can confirm:

echo 'Count: '.$instance['count'];

Returns: Count: 5

I am running the latest stable WordPress (4.1), with no plugins apart from ACF (Advanced Custom Fields) – just my custom theme. Disabling this plugin has no effect, and default WordPress theme (2015) has the same issue.

I’m struggling to understand why this is happening.