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

2024-06-22

我正在 WordPress 中开发一个新闻网站,我需要在引导程序轮播中显示前三篇文章,我的问题是我需要仅在三个元素中的第一个元素添加“active”类,但实际上不需要不知道该怎么做。这是我的代码:

<?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;
?>

但它只是给我打印了“活跃”的话。

感谢您的帮助


您需要设置 $i ,以便可以计算循环的次数并用它执行一些逻辑,就像下面的示例一样。不过,您应该能够在类 active 周围执行 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++;
}
?>
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何将“活动”类添加到轮播第一个元素 的相关文章

随机推荐