user1688793
user1688793

Reputation:

count objects in loop (show number)

I want display wordpress loop but I want only show count of items in the loop filtered by a custom field value. I don't want to show the title or the content, only the count. This is what I have:

<?php query_posts('meta_key=city&meta_value=Seelbach');  ?>
<?php $count = 0; ?>
<?php if (have_posts()) : ?>
<?php while (have_posts()) : the_post(); ?>
    <?php $count++; //increment the variable by 1 each time the loop executes ?>

            <div>
                <?php if ($count==1) {
                    echo "1";
                }
                elseif ($count==2) {
                    echo "2";
                }
                elseif ($count==3) {
                    echo "3";
                }
                elseif ($count==4) {
                    echo "4";
                } ?>
            </div>
<?php endwhile; endif; ?>

but the output is "1 2" - he shows each item and gives it a number but i only want to show the count of ALL (in this case 2 ... ) items that fit to my meta_value. that means i only want to show the "2".

Upvotes: 0

Views: 1988

Answers (3)

Steve
Steve

Reputation: 20469

You dont need a loop to get the total number, simply use count on the posts array returned by get_posts:

echo count(get_posts(array('meta_key' => 'city', 'meta_value' => 'Seelbach')));

Edit as per comment:

$count = count(get_posts(array('meta_key' => 'city', 'meta_value' => 'Seelbach')));

if($count){
    //your link code here
}

Upvotes: 0

Bas
Bas

Reputation: 61

If you want to get the total number of posts inside the loop, do something like this (result will always be 2):

<?php $posts = query_posts('meta_key=city&meta_value=Seelbach');  ?>

    <?php if (have_posts()) : ?>

        <?php while (have_posts()) : the_post(); ?>
        <?php
            <div>
                <?php echo count($posts); ?>
            </div>
<?php endwhile; endif; ?>

If you need the posts count only once, place the div outside the loop

<?php $posts = query_posts('meta_key=city&meta_value=Seelbach');  ?>

        <?php if (have_posts()) : ?>

           <?php while (have_posts()) : the_post(); ?>
               <?php
               // do something with post data
               ?>
           <?php endwhile; ?> 
           <div>
               <?php echo count($posts); ?>
           </div>
 <?php endif; ?>

Upvotes: 0

shabeer
shabeer

Reputation: 1064

if you want the total count you can get it like this

<?php query_posts('meta_key=city&meta_value=Seelbach');  ?>
            <?php $count = 0; ?>
            <?php if (have_posts()) : ?>
            <?php while (have_posts()) : the_post(); ?>
            <?php $count++; //increment the variable by 1 each time the loop executes ?>
            <?php endwhile; endif; ?>
           <?php echo "Count".$count; ?>

Upvotes: 1

Related Questions