Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

WP PHP – Foreach adding different classname – how does it work?

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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>

>Solution :

Add the index to your foreach loop:

foreach ($postslist as $index => $post) :

and use that to append to the class name:

<div class="testrun<?= $index ?>">

As long as the array is an indexed array, you’ll get testrun0, testrun1, testrun2 etc.

If you want to start with 1 instead of 0, just change it to:

<div class="testrun<?= $index + 1 ?>">
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading