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

Lui*_*nza 3 php wordpress carousel twitter-bootstrap

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

<?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>';
}
?>
Run Code Online (Sandbox Code Playgroud)

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

$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;
?>
Run Code Online (Sandbox Code Playgroud)

但它只是给我打印了“活动”字样。

谢谢你的帮助

Ale*_*one 5

您需要设置 $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++;
}
?>
Run Code Online (Sandbox Code Playgroud)