Home > Back-end >  How to add a class to all elements when displaying a post?
How to add a class to all elements when displaying a post?

Time:10-01

Using the get_posts() method, I get and display the last 5 posts. They are displayed as a slider. Each slide is a different color. Only 3 colors: yellow, green and blue. How can I add a class to each of the 5 slides to give a different background? The first 3 slides should be yellow, green and blue, and the rest should be yellow and green. How can i do this? Now I tried to implement this functionality, but the class on each slide is yellow-slide My Code:

<?php
$last_posts = get_posts(array(
    'numberposts' => 5,
    'orderby'     => 'date',
    'post_type'   => 'post',
));

global $post;

$bgcolor = '';

if ($counter == 0) {
    $bgcolor = 'yellow-slide';
} else if ($counter == 1) {
    $bgcolor = 'green-slide';
} else if ($counter == 2) {
    $bgcolor = 'blue-slide';
} else if ($counter == 3) {
    $bgcolor = 'yellow-slide';
} else {
    $bgcolor = 'green-slide';
}

?>

  <div >
    <div >
      <?php $counter = 0;
                    foreach ($last_posts as $post) :
                        setup_postdata($post); ?>
      <div ></div>
      <?php $counter   ?>
      <?php endforeach;
                    wp_reset_postdata(); ?>
    </div>
  </div>

CodePudding user response:

Your PHP code is executed in the order it's written in, so your if-statements will be executed before you've even started the foreach-loop (and before the variable $counter even exist). It should actually throw a bunch of "Undefined variable: $counter"-warnings/notices.

There is an easier way though.

  • Put the class names in an array
  • Fetch the class from the array on each iteration that matches the array index

Something like this:

$bgcolors = [
    'yellow-slide',
    'green-slide',
    'blue-slide',
    'yellow-slide',
    'green-slide',
];

Then after you've defined that array, you can do:

$counter = 0;
foreach ($last_posts as $post) :
    setup_postdata($post); 
    ?>
    <div ></div>
    <?php $counter   ?>
<?php endforeach;

CodePudding user response:

Please try this and check again.

<?php
$last_posts = get_posts(array(
    'numberposts' => 5,
    'orderby'     => 'date',
    'post_type'   => 'post',
));

?>

  <div >
    <div >
    <?php 
        foreach ($last_posts as $key => $post) :
            setup_postdata($post); 

            $bgcolor = '';
            if ($key == 0) {
                $bgcolor = 'yellow-slide';
            } else if ($key == 1) {
                $bgcolor = 'green-slide';
            } else if ($key == 2) {
                $bgcolor = 'blue-slide';
            } else if ($key == 3) {
                $bgcolor = 'yellow-slide';
            } else {
                $bgcolor = 'green-slide';
            }
                ?>
      <div ></div>

        <?php endforeach;
            wp_reset_postdata(); 
        ?>
    </div>
  </div>
  • Related