自定义分类术语页面中的当前分类项

时间:2015-06-05 16:37:31

标签: php wordpress custom-taxonomy

我有一个名为trailer_type的自定义分类,其中包含longshort项。访问my_site/trailers/short(由模板taxonomy-trailer_type.php提供支持的页面)时,我会以这种方式显示我的分类术语:

$terms = get_terms( 'trailer_type' );
if ( ! empty( $terms ) && ! is_wp_error( $terms ) ) {
    echo '<ul>';
    foreach ( $terms as $term ) {
        echo '<li><a href="' . get_term_link( $term ) . '" title="' . sprintf( __( 'View all post filed under %s', 'my_localization_domain' ), $term->name ) . '">' . $term->name . '</a></li>';
    }
    echo '</ul>';
}

运作良好,但有一种简单的方法来添加“当前”类吗?例如,如果我在“长”页面上,我需要“长”才能在此菜单中拥有“当前”类。

2 个答案:

答案 0 :(得分:4)

您需要查看查询的对象。有几种方法可以做到这一点,这是我倾向于使用的:$wp_query->queried_object - 顾名思义,它返回查询的对象。

在你的情况下,这样的事情应该有效:

$curTerm =  $wp_query->queried_object;
$terms = get_terms( 'trailer_type' );
if ( ! empty( $terms ) && ! is_wp_error( $terms ) ) {
    echo '<ul>';
    foreach ( $terms as $term ) {
        $classes = array();
        if ($term->name == $curTerm->name)
            $classes[] = 'current';
        echo '<li class="'. implode(' ',$classes) .'"><a href="' . get_term_link( $term ) . '" title="' . sprintf( __( 'View all post filed under %s', 'my_localization_domain' ), $term->name ) . '">' . $term->name . '</a></li>';
    }
    echo '</ul>';
}

我正在将类设置为数组,以便将来扩展。您也可以立即将其设置为字符串。

答案 1 :(得分:0)

尝试使用

get_query_var( 'term' )

并检查

if ($term->name == get_query_var( 'term' )){
//make something
}