Brett Golding
Brett Golding

Reputation: 85

Implementing a PHP counter inside of a while loop to wrap list items with ul elements

I am having difficulty implementing a PHP counter, to wrap my list elements in unordered list tags.

I want to wrap around every 3 list elements.

I have been trying to use these previous questions as a guide but to little avail.

easier way to get counter from while loop?

php loop counter bootstrap row

            <?php

            $counter = 0; 

            echo '<ul class="products latestCourses">';

            while ( have_posts() ) : the_post(); ?>

                <?php wc_get_template_part( 'content', 'product' ); ?>

            <?php $counter = $counter++; ?>

            <?php if ($counter%3 == 0) echo '</ul><ul class="products latestCourses">'; ?>

            <?php endwhile; // end of the loop. ?>

This is what I have so far the page template simply contains a list element.

Currently this code is wrapping every list item in an unorder list.

Upvotes: 0

Views: 109

Answers (2)

Yannis Berrouag
Yannis Berrouag

Reputation: 356

<?php $counter = $counter++; ?>

this line is wrong, use either

<?php $counter++; ?>

or

<?php $counter = $counter +1; ?>

Upvotes: 4

Aakash Martand
Aakash Martand

Reputation: 944

Use this for increment by 1
$counter = $counter + 1;

or
$counter = $counter + n;
where 'n' is the desired number by which you want to increment

Upvotes: 1

Related Questions