You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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 the current-lang class only to the currently active language (instead of all items).
  • Security Sanitization: Added esc_attr(), esc_url(), and esc_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_url to 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-lang isn't overriding the flag display in unexpected ways

内容的提问来源于stack exchange,提问作者S.I.

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.09 07:57:30