I've got a custom taxonomy called trailer_type
with terms long
and short
. When visiting my_site/trailers/short
(a page powered by template taxonomy-trailer_type.php
) I display my taxonomy terms this way:
$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>';
}
Works well but is there a simple way to add a "current" class? For example if I'm on the "long" page, I'd need "long" to have "current" class in this menu.
You need to look at the queried object. There's several ways to do it, here's what I tend to use: $wp_query->queried_object
- this returns, as the name implies, the queried object.
In your case, something like this should work:
$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>';
}
I'm setting the classes to an array simply for future expansion. You could set it to a string right away as well.
Try using
get_query_var( 'term' )
and check
if ($term->name == get_query_var( 'term' )){
//make something
}