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

如何为WordPress WPML语言改写插件中的PHP条件判断代码

Solution: Switch Artist Bio Fields Based on WPML Current Language

Got it, let's tackle this WPML language switch for your artist bio fields. Here's a clean, robust solution that follows WPML best practices and handles edge cases like missing secondary language content:

// First, determine the appropriate bio content based on WPML language
if (defined('ICL_LANGUAGE_CODE') && ICL_LANGUAGE_CODE === 'es') {
    // Replace 'es' with your actual secondary language code (e.g., 'fr' for French, 'de' for German)
    // Fallback to default bio if secondary language content is empty
    $bio_content = !empty($artist->secondary_language_bio) 
        ? nl2br((string)$artist->secondary_language_bio) 
        : nl2br((string)$artist->bio_public);
} else {
    // Default language: use the original bio_public field
    $bio_content = nl2br((string)$artist->bio_public);
}

// Append the formatted bio to your post content
$post_content .= "<div class='artist_bio'>" . $bio_content . "</div>";

Key Details & Explanations:

  • WPML Language Check: We use the ICL_LANGUAGE_CODE constant (provided by WPML) to get the current active language. The defined() check ensures we don't throw errors if WPML is deactivated.
  • Language Code Replacement: Swap 'es' with your actual secondary language code (you can find this in WPML → Languages settings, under "Language Code" for each language).
  • Fallback Logic: The !empty() check ensures if the secondary language bio is blank, we fall back to the default bio_public content instead of showing nothing.
  • Type Safety: We keep the (string) cast and nl2br() function from your original code to ensure line breaks are preserved and we avoid issues with non-string values from custom fields.
  • Cleaner Code Structure: By assigning the bio content to a variable first, the code is easier to read and modify later.

Simplified Version (Without Fallback):

If you don't need the fallback (and trust that the secondary language field will always have content), you can use this shorter version:

$bio_content = defined('ICL_LANGUAGE_CODE') && ICL_LANGUAGE_CODE === 'es'
    ? nl2br((string)$artist->secondary_language_bio)
    : nl2br((string)$artist->bio_public);

$post_content .= "<div class='artist_bio'>" . $bio_content . "</div>";

内容的提问来源于stack exchange,提问作者Taylor Latch

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 11:19:24