Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

How can I limit the amount of results returned?

$images = $wpdb->get_col("
    SELECT ID FROM $wpdb->posts
    WHERE post_type = 'attachment'
    AND ID in ($meta)
    ORDER BY menu_order ASC
");
share|improve this question
add comment

3 Answers

up vote 2 down vote accepted
$images = $wpdb->get_col("
    SELECT ID FROM $wpdb->posts
    WHERE post_type = 'attachment'
    AND ID in ($meta)
    ORDER BY menu_order ASC
    LIMIT 5
");

Like @Kaiser suggested you can specify a range (5th to 20th results, a total of 15 results are returned at max) like this:

$images = $wpdb->get_col("
    SELECT ID FROM $wpdb->posts
    WHERE post_type = 'attachment'
    AND ID in ($meta)
    ORDER BY menu_order ASC
    LIMIT 5,20
");
share|improve this answer
    
thanks! I didn't realize i had to put that at the END. –  JonnyPlow Aug 8 '11 at 23:13
    
Don't forget to accept the answer by selecting it :) –  Ashfame Aug 9 '11 at 13:55
    
Deleted my answer as integrated here. @Ashfame Thanks. :) (should have been a comment here). –  kaiser Aug 9 '11 at 14:08
add comment

Why not just use get_posts()?

<?php
$attachments = get_posts( array(
    'post_type' => 'attachment', // post attachments
    'post_mime_type' => 'image', // only images
    'post_parent' => $post->ID,  // children of the current post
    'number_posts' => 5          // <-- THIS IS THE NUMBER OF POSTS LIMIT
) );
?>

I always prefer function calls to raw DB queries.

share|improve this answer
    
Even I prefer that but in some cases, we only need to fetch post IDs and we don't want WordPress to run a full query & cache it. This makes more sense when we are doing other than just displaying data :) –  Ashfame Aug 9 '11 at 13:49
    
In which case, there's also get_children(). ;) –  Chip Bennett Aug 9 '11 at 14:49
    
You misunderstood me. Think of doing an API call to a third party service only for posts matching a certain criteria. :) –  Ashfame Aug 9 '11 at 14:58
    
I would consider a raw-SQL DB query to be the "third party API service call" in this scenario. Using a core-provided query function is generally safer, faster, more efficient, and more forward-compatible than making a raw-SQL DB query. –  Chip Bennett Aug 9 '11 at 15:12
add comment

As an addition to @Ashfame Answer: You can not only set a "hard" limit, but also a range, using LIMIT 1,100 which would bring you the results 1-100.

share|improve this answer
1  
Thanks, I added the suggestion into my answer :) –  Ashfame Aug 9 '11 at 13:47
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.