functions - modifying every other element's class inside while loop

<?php $homePosts = new WP_Query(array('posts_per_page' => 5 ));while ($homePosts-&

<?php 
    $homePosts = new WP_Query(array(
        'posts_per_page' => 5                       
    ));

    while ($homePosts->have_posts()) {
      $homePosts->the_post(); ?>

    <section class="align-right>
        <div class="content">
            <?php the_title(); ?>
            <?php the_content(); ?>                                 
        </div>
    </section>

<?php } wp_reset_postdata(); ?>

The above code is part of my front-page.php. I am trying to modify the class that is in <section class="align-*****">, so that the 1st, 3rd, and 5th sections have class='align-left' and the 2nd, and 4th sections have class='align-right'.

What would be the best approach to modify the class values within a WordPress loop? Would I need to write my own function in functions.php? Use jQuery? Is there a WP function that can help with this?

<?php 
    $homePosts = new WP_Query(array(
        'posts_per_page' => 5                       
    ));

    while ($homePosts->have_posts()) {
      $homePosts->the_post(); ?>

    <section class="align-right>
        <div class="content">
            <?php the_title(); ?>
            <?php the_content(); ?>                                 
        </div>
    </section>

<?php } wp_reset_postdata(); ?>

The above code is part of my front-page.php. I am trying to modify the class that is in <section class="align-*****">, so that the 1st, 3rd, and 5th sections have class='align-left' and the 2nd, and 4th sections have class='align-right'.

What would be the best approach to modify the class values within a WordPress loop? Would I need to write my own function in functions.php? Use jQuery? Is there a WP function that can help with this?

Share Improve this question edited Jun 3, 2019 at 7:55 nmr 4,5672 gold badges17 silver badges25 bronze badges asked Jun 3, 2019 at 5:12 psyminrhee79psyminrhee79 113 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 0
<?php 
$homePosts = new WP_Query(array(
    'posts_per_page' => 5                       
));

$count = 1;

while ($homePosts->have_posts()) {
  $homePosts->the_post(); 

    if ( $count % 2 == 0 ) {
        $class = 'right';
    } else {
        $class = 'left';
    }

?>

<section class="align-<?php echo $class; ?>" >
    <div class="content">
        <?php the_title(); ?>
        <?php the_content(); ?>                                 
    </div>
</section>

<?php 
$count++;

} wp_reset_postdata(); 

?>

You can try this code

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745441970a4627870.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信