如何将“活动”类添加到轮播第一个元素

时间:2016-10-10 14:04:53

标签: php wordpress twitter-bootstrap carousel

我正在Wordpress中开发一个新闻网站,我需要在前三个帖子的bootstrap轮播中显示,我的问题是我只需要在三个元素中的第一个添加“活动”类,但是真的不知道该怎么做。这是我的代码:

<?php
$args = array('numberposts' => '3');
$recent_posts = wp_get_recent_posts($args);
foreach ($recent_posts as $recent) {
echo '<div class="item active"><a href="' . get_permalink($recent["ID"]) . '" title=" ' . esc_attr($recent["post_title"]) . '" >' .$recent["post_date"] . ': <strong>' .$recent["post_title"] . '</strong></a></div>';
}
?>

我已经尝试过在这个网站上找到的答案(这个):

$isFirst = true;
foreach ($recent_posts as $recent) {
echo '<div class="item' . $isFirst ? ' active' : '' . '"><a href="' . get_permalink($recent["ID"]) . '" title=" ' . esc_attr($recent["post_title"]) . '" >' .$recent["post_date"] . ": <strong>"  .$recent["post_title"] . '</strong></a></div>';
$isFirst = false;
?>

但它只是打印了“活跃”字样。

感谢您的帮助

1 个答案:

答案 0 :(得分:3)

你需要设置$ i,这样你就可以计算你完成循环的次数并用它做一些逻辑,就像我下面的例子一样。而不是像我下面所做的那样有两行几乎相同的代码,你应该能够在类活动的条件下执行if条件权限。我没有这样做,所以你可以清楚地看到数组循环的条件和计数。

<?php
$args = array('numberposts' => '3');
$recent_posts = wp_get_recent_posts($args);
$i = 0;
foreach ($recent_posts as $recent) {

if ($i == 0) {
    echo '<div class="item active"><a href="' . get_permalink($recent["ID"]) . '" title=" ' . esc_attr($recent["post_title"]) . '" >' .$recent["post_date"] . ': <strong>' .$recent["post_title"] . '</strong></a></div>';
} else {
    echo '<div class="item"><a href="' . get_permalink($recent["ID"]) . '" title=" ' . esc_attr($recent["post_title"]) . '" >' .$recent["post_date"] . ': <strong>' .$recent["post_title"] . '</strong></a></div>';
}
$i++;
}
?>
相关问题