将多个While循环合并为一个

时间:2016-01-06 15:01:50

标签: wordpress while-loop

我正在努力将Nivo Slider集成到WordPress页面中,我希望将其与标题一起使用,并最终使代码工作,如下所示;

<div class="slider-wrapper theme-default">
    <div id="slider" class="nivoSlider"> 

        <?php 

        $slides = array (
            'post_type'      => 'slides',
            'posts_per_page' => -1,
        );

        $count=1;

        $slideshow = new WP_Query( $slides ); 

        while ( $slideshow->have_posts() ) : $slideshow->the_post(); ?>

            <?php $feat_image_url = wp_get_attachment_url( get_post_thumbnail_id() ); ?>

            <a href="<?php the_field('slide_link'); ?>"><img src="<?php echo $feat_image_url; ?>" alt="<?php echo the_title(); ?>" title="#htmlcaption<?php echo $count ?>"/></a>

            <?php $count++; ?>

        <?php endwhile; ?>

    </div>

        <?php

        $count=1;

        while ( $slideshow->have_posts() ) : $slideshow->the_post(); ?>

            <div id="htmlcaption<?php echo $count ?>" class="nivo-html-caption">
                <strong>This</strong> is an example of a <em>HTML</em> caption with <a href="#">a link</a>.
            </div>

            <?php $count++; ?>

        <?php endwhile;

        wp_reset_query(); ?>

</div>

我担心我不必要地添加了2个While循环和计数器。有没有办法通过组合循环并仅使用一个计数器来提高效率?

1 个答案:

答案 0 :(得分:0)

您可以执行以下操作,使用临时var作为标题并在循环后输出:

$captions = '';
while ( $slideshow->have_posts() ) : $slideshow->the_post(); ?>
    <?php $feat_image_url = wp_get_attachment_url( get_post_thumbnail_id() ); ?>
    <a href="<?php the_field('slide_link'); ?>"><img src="<?php echo $feat_image_url; ?>" alt="<?php echo the_title(); ?>" title="#htmlcaption<?php echo $count ?>"/></a>
    <php $captions .= '<div id="htmlcaption' . $count . '" class="nivo-html-caption"><strong>This</strong> is an example of a <em>HTML</em> caption with <a href="#">a link</a></div>'; ?>
    <?php $count++; ?>
<?php endwhile; ?>

然后代替你的第二个循环:

echo $captions;