How to limit displayed posts on wordpress

How would I edit the following code, so that only 2 of the posts are echoed instead of 3

   <?php

                            global $more; $more = false; # some wordpress wtf logic

                            $num_of_posts = $wp_query->post_count;

                            $current = -1;

                                $cat_id = get_cat_ID(single_cat_title('', false));
                                if(!empty($cat_id))
                                {
                                    $query_string.= '&cat='.$cat_id;
                                }

                            query_posts($query_string);

                            if (have_posts()) : while (have_posts()) : the_post(); $current++


                        ?> 

                            <?php if($current == 0) { ?>

Related posts

Leave a Reply

3 comments

  1. The WP_Query class has several methods that push various information to the resulting $wp_query object:

    • $wp_query->found_posts shows the total number of posts
    • $wp_query->numberposts the same, but it’s deprecated (still works)
    • $wp_query->posts_per_page if you got a paged query, you can see how many per page you want to display
    • $wp_query->current_post is the currently looped through post

    So if you want to abort, simply go and

    if ( 3 < $wp_query->current_post )
        break;
    

    to stop the rest of the loop.

  2. Another option would be to jump in use the post_limits filter. The following example summed up as mini-plugin or mu-plugin.

    <?php
    /* Plugin Name: (#90428) Posts Limit */
    add_filter( 'post_limits', 'wpse90428_post_limits' );
    function wpse90428_post_limits( $limit )
    {
        if ( is_archive() )
            return 'LIMIT 0, 2';
    
        return $limit;
    }
    

    You could as well go further and set it during the parse_request (earlier) or pre_get_posts filter.

    <?php
    /* Plugin Name: (#90428) Posts Limit */
    add_filter( 'parse_requests', 'wpse90428_post_limits' );
    function wpse90428_post_limits( $query )
    {
        if ( $query->is_archive() )
            $query->set( 'posts_per_page', 3 );
    
        return $query;
    }
    

    You’ll just have to tweak this to your needs.