如何将活动类添加到第一个 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>

如果未设置,则使用类字符串分配变量

在后续迭代中...设置时,将其分配给空字符串。

<!-- 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 ) {
$class = !isset( $class ) ? ' class="my-class"' : '';
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>';
}
}
?>
</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>

最新更新