I am trying to learn some PHP by creating my own WordPress theme. I seem to have struck a blank on a problem and Google aint helping much!
I am trying to add a unique classname to each item within my foreach loop. I have gotten it to work with the post ID but this is not a viable solution.
The problem:
I am creating 3 boxes with the 3 latest posts. All posts needs a different classname so they can be placed within a CSS grid (hard to explain the design, but that’s essentially what I need). My idea was that each post could get a classname or ID like "item1" for the first, "item2" for the next etc. So that on each loop it adds +1 to the classname.
How would I get around doing that? Building on my knowledge of React I wondered if there is a key-function alike it in PHP?
Here is my code for reference:
<section class="classmain">
<?php
$args = array( 'numberposts' => 3, 'order'=> 'ASC', 'orderby' => 'title' );
$postslist = get_posts( $args );
foreach ($postslist as $post) : setup_postdata($post); ?>
<div class="testrun">
<img src="<?php the_post_thumbnail_url('blog-small');?>" alt="<?php the_title();?>" style="margin-right: 20px">
<br />
<!-- <?php the_date(); ?>
<br />
<?php the_title(); ?>
<br />
<?php the_excerpt(); ?>
<br /> -->
</div>
<?php endforeach; ?>
</section>
2
Answers
You can try something like this.
Add the index to your foreach loop:
and use that to append to the class name:
As long as the array is an indexed array, you’ll get
testrun0
,testrun1
,testrun2
etc.If you want to start with
1
instead of0
, just change it to: