最好的解决方案是创建一个创建输出的函数。在上瘾中,这为使用功能选项提供了更大的灵活性。
经过测试的代码如下:
<?php
function wp_bootstrap_carousel($args = \'\', $visible = 3, $active = 0) {
// cannot show more than 12 items at once
if ( ! intval($visible) || $visible > 12 ) return false;
$query = new WP_Query($args);
if ($query->have_posts() ) {
$i = -1;
$output = \'\';
// calculate the span class depending on desired visible items
$span = floor(12 / $visible);
// if 12 is not a perfect multiple of visible items, calculate the residue
$span_residue = 12%$visible;
$slides = 0;
while ( $query->have_posts() ) :
$i++;
$query->the_post();
// set active only the desired active item
$item_class = $i == $active ? \'item active\' : \'item\';
$u = ( ($i == 0) || $i % ($visible) == 0 ) ? 0 : $u+1;
if ( $u == 0 ) {
$slides ++;
// open item div if needed
$output .= sprintf(\'<div class="%s">\', $item_class);
}
$output .= sprintf(\'<div class="span%d">%s</div>\', $span, get_the_title() );
// close item div if needed
if ( $u == ($visible-1) || $i == ($query->post_count-1) ) {
// when on last post we always need to close the current item div,
// if total is not divisible by visible we insert a "fake" item
if ( $u != ($visible-1) ) $span_residue += ( ($visible-1) - $u ) * $span;
if ( $span_residue > 0 ) {
$output .= sprintf(\'<div class="span%d"> </div>\', $span_residue);
}
$output .= \'</div>\';
}
endwhile;
return array(\'items\' => $output, \'total\' => $query->post_count, \'slides\' => $slides);
}
return false;
}
// query args
$args = array(
\'posts_per_page\' => -1,
\'cat\' => 3
);
$active = 0; // the slide first visible
$carousel = wp_bootstrap_carousel($args, 5, $active);
if ( is_array($carousel) && $carousel[\'total\'] > 0 ) :
?>
<div id="myCarousel" class="carousel slide">
<ol class="carousel-indicators">
<?php for ($i = 0; $i < $carousel[\'slides\']; $i++ ) : ?>
<li data-target="#myCarousel" data-slide-to="<?php echo $i; ?>"<?php if ($i==$active) { ?> class="active"<?php } ?>></li>
<?php endfor; ?>
</ol>
<!-- Carousel items -->
<div class="carousel-inner">
<?php echo $carousel[\'items\']; ?>
</div>
</div>
<?php endif; ?>