views:

60

answers:

1

I'm unable to substitute posts_per_page with showposts in order to limit the number of posts returned in a list. When I use showposts, the resulting menu list is correctly displayed according to the number of posts I specify in the showposts limiter. However, when I use posts_per_page, the post limiter number appears to be irrelevant. The resulting list shows all posts, exceeding the limiter count.

Examples:

This works perfectly:

$myrecentposts = get_posts(array('post_not_in' => get_option('sticky_posts'), 'cat' => "-$cat,-$catHidden",'showposts' => $cb2_recent_count));
foreach($myrecentposts as  $idxrecent=>$post) {

However, when I sub in posts_per_page, this DOES NOT work...

$myrecentposts = get_posts(array('post_not_in' => get_option('sticky_posts'), 'cat' => "-$cat,-$catHidden",'posts_per_page' => $cb2_recent_count));
foreach($myrecentposts as  $idxrecent=>$post) {

*I'm only trying to get posts_per_page to work because I understand that showposts has been deprecated.

A: 

showposts is deprecated. However, posts_per_page is for use with query_posts(), or more specifically, WP_Query::query().

numberposts is the equivalent argument for get_posts().

NOTE: I removed my original answer concerning incorrect handling of arguments inside get_posts().

posts_per_page is not a valid argument for get_posts() for semantic reasons, since it suggests the idea of pagination, something which get_posts() does not support.

For clarity, and on behalf of @RichardM's comment, here's the skinny I originally wrote;


It's down to how get_posts() parses the arguments before passing them on to WP_Query.

I've cut it down to the real basics here;

function get_posts($args = null)
{
    $defaults = array('numberposts' => 5);
    $r = wp_parse_args($args, $defaults);

    if (!empty($r['numberposts']))
        $r['posts_per_page'] = $r['numberposts'];

    $get_posts = new WP_Query;
    return $get_posts->query($r);
}

See how numberposts overwrites posts_per_page, not accounting the condition that posts_per_page is being passed?

TheDeadMedic
So I should replace showposts with numberposts? And numberposts is not on the endangered list I suppose :)
Scott B
Thanks DM, works like a charm!
Scott B
I think your original answer was useful, the edit seems to obscure the problem somewhat. As far as I'm aware there is nothing stopping you from using pagination with `get_posts`, other than it being semantically confusing.
Richard M
I guess you **can** use pagination with `get_posts`, but it was never really designed for it - personally I feel `get_posts` should do what it says on the tin: just 'get posts'! If you want to get more fancy, roll onto `query_posts`.
TheDeadMedic