php - 如何将活动类添加到第一个 foreach 项目?
问题描述
尝试将一个活动类添加到此循环中的第一个 foreach a href
<!-- Gallery Filter -->
<div id="filter-by" class="clearfix">
<a href="#" data-filter="gallery-item" class="active"><?php esc_html_e( 'All', 'framework' ); ?></a><?php
$status_terms = get_terms( array( 'taxonomy' => 'property-status' ) );
if ( ! empty( $status_terms ) && is_array( $status_terms ) ) {
foreach ( $status_terms as $status_term ) {
echo '<a href="' . get_term_link( $status_term->slug, $status_term->taxonomy ) . '" data-filter="' . $status_term->slug . '" title="' . sprintf( __( 'View all Properties having %s status', 'framework' ), $status_term->name ) . '">' . $status_term->name . '</a>';
}
}
?>
</div>
解决方案
我所做的是设置一个$count
变量来检查循环是第一个还是其他,如果循环有$count = 0
那么你的类将被显示,或者如果循环是第二个或更多,则不会显示该类。
<div id="filter-by" class="clearfix">
<a href="#" data-filter="gallery-item" class="active"><?php esc_html_e( 'All', 'framework' ); ?></a><?php
$status_terms = get_terms( array( 'taxonomy' => 'property-status' ) );
if ( ! empty( $status_terms ) && is_array( $status_terms ) ) {
$count = 0;
foreach ( $status_terms as $status_term ) {
$class = ($count == 0)?'class="active"':'';
echo '<a '. $class .' href="' . get_term_link( $status_term->slug, $status_term->taxonomy ) . '" data-filter="' . $status_term->slug . '" title="' . sprintf( __( 'View all Properties having %s status', 'framework' ), $status_term->name ) . '">' . $status_term->name . '</a>';
$count++;
}
}
?>
</div>
推荐阅读
- flutter - 颤振可滚动堆栈,顶部有图像,底部有容器,与圆形边框重叠
- wcf - DexExpress XPO WCF DataStoreService 性能不佳
- reactjs - qs 库没有像文档中那样对字符串进行编码
- angular - 对于嵌套的 for 循环,角度虚拟滚动无法正常工作
- javascript - 异步等待 API 调用后 Reactjs 状态不更新
- javascript - Angular 单元测试验证子组件的方法调用
- reactjs - reactjs中的元素类型无效
- javascript - PdfMake getBase64 undefined - React JS
- python-3.x - 在 aws CodePipelines 上工作,堆栈创建每次都失败
- java - Android Studio:有没有办法更改 ArrayAdapter 上显示的文本?