for loop counter $i=1;$i<=3;$i++ in wordpress is creating duplicates

niceoneishere
niceoneishere used Ask the Experts™
on
I am using the below php code to add a class to each post from a specific category. The counter adds the number to class but each of the is adding 3 times. here is my mark up
	 <ul class="ul">	 
	 <?php query_posts('showposts=3&cat=3&orderby=rand'); if (have_posts()) : while (have_posts()) : the_post(); ?>
	 <?php for ( $i=1; $i<=3; $i++ ) { ?>
	 <li class="li<?php echo $i ?>"><a href="<?php $postid = $wp_query->post->ID; echo get_post_meta($postid, '_wpb_nsl_text', true);  ?>" title="<?php the_title_attribute(); ?>"><?php print $post->post_title; ?></a>
	 <a href="<?php $postid = $wp_query->post->ID; echo get_post_meta($postid, '_wpb_nsl_text', true);  ?>"><?php the_post_thumbnail('blog-post-image'); ?></a>
	</li>
		<?php } ?>
	<?php endwhile; else : endif; ?>
	<?php wp_reset_query(); ?>
	</ul>

Open in new window

The result is like below and as you can see its creating 3 li's for each post instead of only one
<ul class="ul>
 <li class="li1">post 1 </li>
 <li class="li2">post 1 </li>
 <li class="li3">post 1 </li>
 <li class="li1">post 2 </li>
 <li class="li2">post 2 </li>
 <li class="li3">post 2 </li>
 <li class="li1">post 3 </li>
 <li class="li2">post 3 </li>
 <li class="li3">post 3 </li>
</ul>

Open in new window

What I am looking is
<ul class="ul>
 <li class="li1">post 1 </li>
 <li class="li2">post 2 </li>
 <li class="li3">post 3 </li>
</ul>

Open in new window

What am I missing?
Thanks
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Top Expert 2015
Commented:
You have a for loop inside of a while loop. The while loop runs three times because you requested three posts. You have set the for loop to run three times also. 3 x 3 = 9

You want something more along these lines (not tested):
 <ul class="ul">
<?php
// The Query
query_posts( 'showposts=3&cat=3&orderby=rand' );

// The Loop
$i = 1;
while ( have_posts() ) : the_post();
    $postid = $wp_query->post->ID;
    $postmeta = get_post_meta($postid, '_wpb_nsl_text', true);
    echo '<li class="li' . $i . '"><a href="' .  $postmeta  .  '" title="' . the_title_attribute() . '">' .  $post->post_title . '</a>
	 <a href="' . $postmeta . '">' . the_post_thumbnail('blog-post-image') . '</a>
	</li>';
	$i++;
endwhile;

// Reset Query
wp_reset_query();
?>
</ul>

Open in new window

Author

Commented:
Thanks :)

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial