如何为WordPress自定义分类blogs_taxanomy的当前活跃分类链接添加高亮颜色?
How to Highlight Active Custom Taxonomy Link in WordPress
Got it, let's get that active category highlight working for your blogs_taxanomy custom taxonomy. Here's the step-by-step fix:
Step 1: Update Your PHP Code
First, we need to detect the current active taxonomy term on the page, then add a special class to the matching link in your loop. I've fixed syntax issues in your original code and added the active check logic:
<?php // Grab the current taxonomy term being viewed (works on archive pages) $current_term = get_queried_object(); // Fetch all terms for your custom taxonomy $terms = get_terms( array( 'taxonomy' => 'blogs_taxanomy', 'hide_empty' => false, ) ); // Only run the loop if we have valid terms if ( ! empty( $terms ) && ! is_wp_error( $terms ) ) : foreach ( $terms as $term ) : // Check if the current loop term matches the page's active term $is_active = ( isset( $current_term->term_id ) && $current_term->term_id === $term->term_id ) ? 'active' : ''; ?> <div class="blog-container-control center" > <div class="col-12 pt-2 pb-2 blog-container-inner-control"> <a href="<?php echo esc_url( get_term_link( $term ) ); ?>"> <span class="link <?php echo esc_attr( $is_active ); ?>"><?php echo esc_html( $term->name ); ?></span> </a> </div> </div> <?php endforeach; endif; ?>
Key Changes Breakdown:
- Added
get_queried_object()to capture the current taxonomy term the user is viewing (this works perfectly on your custom taxonomy archive pages). - Added an
$is_activevariable that compares the loop's term ID to the page's active term ID—if they match, it adds theactiveclass to the link text. - Used
esc_url()andesc_html()for security (WordPress best practice to prevent XSS vulnerabilities). - Wrapped the loop in an error check to handle cases where no terms exist or
get_terms()returns an error.
Step 2: Add CSS for Highlight Style
Now define what the highlighted state looks like. Add this to your theme's style.css file or custom CSS section:
/* Style for active taxonomy link */ .blog-container-inner-control .link.active { background-color: #2563eb; /* Replace with your preferred highlight color */ color: #ffffff; /* Text color for the active state */ padding: 4px 12px; /* Optional: add padding for better visual appeal */ border-radius: 4px; /* Optional: rounded corners for a softer look */ }
Edge Case Notes
- If you're using this code on a single post page (not a taxonomy archive), adjust the logic to fetch the post's associated terms with
wp_get_post_terms(), then compare those IDs to the loop terms. - Double-check your taxonomy slug: make sure
blogs_taxanomyis the exact slug you used when registering the taxonomy (typos here will break the code).
内容的提问来源于stack exchange,提问作者匿名用户
相关产品推荐
相关产品推荐

