[英]Current taxonomy item in custom taxonomy term page
我有一个名为trailer_type
的自定义分类法,带有long
和short
术语。 当访问my_site/trailers/short
(由taxonomy-trailer_type.php
my_site/trailers/short
模板提供支持的页面)时,我以这种方式显示我的分类法术语:
$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>';
}
效果很好,但是有没有简单的方法添加“当前”类? 例如,如果我在“长”页面上,则需要“长”才能在此菜单中具有“当前”类。
您需要查看查询的对象。 有几种方法可以执行此操作,这是我倾向于使用的方法: $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>';
}
我将类设置为数组只是为了将来扩展。 您也可以立即将其设置为字符串。
尝试使用
get_query_var( 'term' )
并检查
if ($term->name == get_query_var( 'term' )){
//make something
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.