mattpark22
mattpark22

Reputation: 751

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.

Upvotes: 1

Views: 12521

Answers (3)

Meysam Jafari
Meysam Jafari

Reputation: 65

for resolve just define array out of WP_Query! like this:

$args=[
'category_name'  => '',
'posts_per_page' => $home_post_count,
'paged'          => $paged];

$query = new WP_Query( $args);

Upvotes: 0

An Ly
An Ly

Reputation: 1

I know this was asked 6 years ago, but this still was driving me crazy, so maybe it'll help someone. There are two options that I needed for posts_per_page to work:

        'ignore_sticky_posts'   => true,
        'paged'                 => 1,

I've tried to use them separately and it didn't help, only when both are set everything works fine.

Upvotes: 0

Matías Chomicki
Matías Chomicki

Reputation: 107

Check if $instance['count'] has the desired value for posts_per_page. For example, if you want 5 posts, $instance['count'] should be = 5;

$instance['count'] = 5; //just for the sake of the test

Upvotes: 2

Related Questions