WPML语言切换器当前语言国旗不显示问题求助
Fixing WPML Language Switcher Active Flag Display Issue
Looks like the core problem here is that your current code applies the current-lang class to every single language list item instead of only the active one—plus there's no check to distinguish which language is actually the currently active one. That's why you're stuck seeing the first flag repeated for the active language.
Here's the revised code that correctly identifies the active language and displays its proper flag:
<?php if(function_exists('icl_get_languages')): $languages = icl_get_languages('skip_missing=0'); if(count($languages) >= 1): ?> <div class="topbar-lang-switcher"> <ul class="lang-switcher-polylang"> <?php foreach((array)$languages as $language): ?> <!-- Only apply current-lang class to the active language --> <li class="<?php echo $language['active'] ? 'current-lang' : ''; ?>"> <a rel="alternate" hreflang="<?php echo esc_attr($language['language_code']); ?>" href="<?php echo esc_url($language['url']); ?>"> <!-- Add fallback to avoid broken images if flag URL is missing --> <?php if(!empty($language['country_flag_url'])): ?> <img src="<?php echo esc_url($language['country_flag_url']); ?>" alt="<?php echo esc_attr($language['native_name']); ?>" title="<?php echo esc_attr($language['native_name']); ?>" /> <?php endif; ?> <span><?php echo esc_html($language['language_code']); ?></span> </a> </li> <?php endforeach; ?> </ul> </div> <?php endif; endif; ?>
Key Fixes & Improvements:
- Active Language Detection: Used WPML's built-in
$language['active']boolean field to apply thecurrent-langclass only to the currently active language (instead of all items). - Security Sanitization: Added
esc_attr(),esc_url(), andesc_html()to clean up output—this is a critical WordPress best practice to prevent XSS vulnerabilities. - Flag Fallback: Added a check for empty
country_flag_urlto avoid broken image links if a language doesn't have a flag assigned in WPML settings. - Readability: Indented and formatted the code to make it easier to scan and maintain.
If you still run into issues after this change, double-check two things:
- Each language in your WPML settings has a flag properly assigned
- Your CSS for
.current-langisn't overriding the flag display in unexpected ways
内容的提问来源于stack exchange,提问作者S.I.
相关产品推荐
相关产品推荐

