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 can I echo out the count of within a foreach loop? I want to change the class of the div below so it's menu-button-1, menu-button-2 etc etc:

    <?php 
$pages = get_children(array('orderby' => 'menu_order', 'order' => 'asc'));
foreach($pages as $post) {
setup_postdata($post);
$fields = get_fields();
?>

    <div class="menu-button-(insert counter here)">
        <a href="<?php echo get_page_link( $post->ID ); ?>"><?php echo $post->post_title; ?></a>
    </div>
<?php
}
wp_reset_query();
?>

So I want it to output something like this - <div class="menu-button-1"> then <div class="menu-button-2"> and so on each time it goes through the loop.

share|improve this question

1 Answer 1

up vote 3 down vote accepted

Insert a new $counter variable before the foreach loop starts, and at the very end of the loop, call $counter++ to increment the number. In the middle, just echo out the $counter variable.

<?php 
$pages = get_children(array('orderby' => 'menu_order', 'order' => 'asc'));
// Add a counter before foreach starts
$counter = 1;
foreach($pages as $post) {
setup_postdata($post);
$fields = get_fields();
?>



<div class="menu-button-<?php echo $counter; /* echo out counter */ ?>">
        <a href="<?php echo get_page_link( $post->ID ); ?>"><?php echo $post->post_title; ?></a>
    </div>
<?php
$counter++; // increment before foreach ends
}
wp_reset_query();
?>
share|improve this answer

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.