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 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) { ?>
share|improve this question
add comment

3 Answers

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

$num_post = 1;
while ( have_posts() && ($num_post++ < 3) ) : ...
share|improve this answer
add comment

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.

share|improve this answer
add comment

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.

share|improve this answer
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.