首页 > 解决方案 > 如何将活动类添加到第一个 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>

标签: phpwordpress

解决方案


我所做的是设置一个$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>

推荐阅读