如何在第一个foreach项目中添加活动班级?

时间:2018-10-14 01:49:43

标签: php wordpress

尝试将活动类添加到此循环中第一个for 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>

2 个答案:

答案 0 :(得分:0)

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

在随后的迭代中……设置它后,将其分配给一个空字符串。

<!-- 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>

答案 1 :(得分:0)

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