skip to Main Content

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


  1. You can try something like this.

    <?php
    
    $i = 1;
    foreach ($postslist as $post) :  setup_postdata($post); ?> 
        <div class="testrun <?php echo "item".$i; ?>">
            <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 $i++; endforeach; ?>
    
    Login or Signup to reply.
  2. 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 ?>">
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search