最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin1浏览0评论
<?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

发布评论

评论列表(0)

  1. 暂无评论