2

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
");
2
$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
");
  • thanks! I didn't realize i had to put that at the END. – JonnyPlow Aug 8 '11 at 23:13
  • Deleted my answer as integrated here. @Ashfame Thanks. :) (should have been a comment here). – kaiser Aug 9 '11 at 14:08
2

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.

  • 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
0

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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