Limit amount of results returned

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
");

Related posts

Leave a Reply

3 comments

  1. $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
    ");
    
  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.

  3. 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.