如何为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_CODEconstant (provided by WPML) to get the current active language. Thedefined()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 defaultbio_publiccontent instead of showing nothing. - Type Safety: We keep the
(string)cast andnl2br()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
相关产品推荐
相关产品推荐

