0

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.

1 Answer 1

4

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();
?>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.