1

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) { ?>

3 Answers 3

1

You just have to check/count how many posts you alreay handled.

$num_post = 1;
while ( have_posts() && ($num_post++ < 3) ) : ...
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.

1

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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