简体   繁体   English

在while循环中更改第一个元素?

[英]Change first element in while loop?

I have a while loop that displays HTML. 我有一个while循环,显示HTML。

However, I need a different element for the first iteration only. 但是,我只需要为第一次迭代使用其他元素。

How can I manage this? 我该如何处理? This is my code: 这是我的代码:

<?php
if (have_posts()) :
    while (have_posts()) :
        the_post();
        $image = wp_get_attachment_image_src( get_post_thumbnail_id( $post->ID ), 'single-post-thumbnail' );
        ?>

        <div class="item" style="background-size:cover; background-image: url(<?php echo $image[0]; ?>); width: 100%; min-height: 300px;">
            <div class="carousel-caption">
                <h3><?php the_title(); ?></h3>
                <p><?php comments_number( 'Pas de commentaires', '1 commentaire', '% commentaires' ); ?></p>
            </div>
        </div>

        <?php
    endwhile;
endif;
?>

Thanks for the help ! 谢谢您的帮助 !

Try this code 试试这个代码

<?phph $flag = 1; ?>

<?php if (have_posts()) : ?>

    <?php while (have_posts()) : the_post(); ?>

    <?php if($flag) { 

                   DO YOUR WORK;


                   $flag = 0;
                    }  ?>

   Rest of your code.

When the script will run for the first time it will find that the FLAG is true so you can do something different with the first loop. 当脚本第一次运行时,它将发现FLAG为true,因此您可以对第一个循环执行其他操作。 then the FLAG will become false. 那么FLAG将变为假。 SO on next loop it wont get inside this 'if' which is used for first loop only 因此,在下一个循环中,它将不会进入仅用于第一个循环的“ if”内部

Your complete code: 您的完整代码:

<?php
if (have_posts()) :
    $flag = 1;
    while (have_posts()) : the_post();
        if($flag == 1) { 

                   PUT YOUR CODE HERE;    

                   $flag = 0;
                    }

        $image = wp_get_attachment_image_src( get_post_thumbnail_id( $post->ID ), 'single-post-thumbnail' );
        ?>

        <div class="item" style="background-size:cover; background-image: url(<?php echo $image[0]; ?>); width: 100%; min-height: 300px;">
            <div class="carousel-caption">
                <h3><?php the_title(); ?></h3>
                <p><?php comments_number( 'Pas de commentaires', '1 commentaire', '% commentaires' ); ?></p>
            </div>
        </div>

        <?php
    endwhile;
endif;
?>

Thanks. 谢谢。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM