我已经创建了一个自定义的帖子类型,我正试图将其实现到CSS滑块中。为了做到这一点,我创建了一个自定义模板,并添加了计数器,以获得每个新帖子的唯一ID。
这是我当前的循环:
<div class="gallery autoplay items-3">
<?php
$args = array(
\'post_type\' => \'referanse\'
);
$referanser = new WP_Query( $args );
if( $referanser->have_posts() ) {
$itemcounter = 1;
$controlcounter = 1;
while( $referanser->have_posts() ) {
$referanser->the_post();
?>
<div id="item-<?php echo $itemcounter++; /* echo out $itemcounter */ ?>" class="control-operator"></div>
<figure class="item">
<h1><?php the_title() ?></h1>
</figure>
<div class="controls">
<a href="#item-<?php echo $controlcounter++; /* echo out $controlcounter */ ?>" class="control-button">•</a>
</div>
<?php
}
}
else {
echo \'Ops, ingen referanser enda...\';
}
?>
</div>
但是,标记不是我想要的,我希望它显示如下:
<div class="gallery autoplay items-3">
<div id="item-1" class="control-operator"></div>
<div id="item-2" class="control-operator"></div>
<div id="item-3" class="control-operator"></div>
<figure class="item">
<h1>Item 1</h1>
</figure>
<figure class="item">
<h1>Item 2</h1>
</figure>
<figure class="item">
<h1>Item 3</h1>
</figure>
<div class="controls">
<a href="#item-1" class="control-button">•</a>
<a href="#item-2" class="control-button">•</a>
<a href="#item-3" class="control-button">•</a>
</div>
</div>
但我得到的是:
<div class="gallery autoplay items-3">
<div id="item-1" class="control-operator"></div>
<figure class="item">
<h1>Item 1</h1>
</figure>
<div class="controls">
<a href="#item-1" class="control-button">•</a>
</div>
<div id="item-2" class="control-operator"></div>
<figure class="item">
<h1>Item 2</h1>
</figure>
<div class="controls">
<a href="#item-2" class="control-button">•</a>
</div>
<div id="item-3" class="control-operator"></div>
<figure class="item">
<h1>Item 3</h1>
</figure>
<div class="controls">
<a href="#item-3" class="control-button">•</a>
</div>
</div>
所以基本上,我要问的是如何更正循环,使其首先显示。控制操作员divs,比实际的职位和最后的控制按钮?
迈克尔
最合适的回答,由SO网友:Rob Vermeer 整理而成
如果不将控件放在while循环中,那么它们每次都会出现。所以可以使用for循环和found_posts
变量来循环while循环前后的项目。
下面的示例。
<div class="gallery autoplay items-3">
<?php
$args = array(
\'post_type\' => \'referanse\'
);
$referanser = new WP_Query( $args );
?>
<?php if( $referanser->have_posts() ) : ?>
<?php for($i=1; $i<=$referanser->found_posts; $i++) : ?>
<div id="item-<?php echo $i; ?>" class="control-operator"></div>
<?php endfor; ?>
<?php while( $referanser->have_posts() ) : $referanser->the_post(); ?>
<figure class="item">
<h1><?php the_title() ?></h1>
</figure>
<?php endwhile; ?>
<div class="controls">
<?php for($i=1; $i<=$referanser->found_posts; $i++) : ?>
<a href="#item-<?php echo $i; ?>" class="control-button">•</a>
<?php endfor; ?>
</div>
<?php else : ?>
Ops, ingen referanser enda...
<?php endif; ?>
</div>