wpml_current_language
Filters the current language code being displayed, allowing modification before it's used.
add_filter( 'wpml_current_language', $callback, 10, 1 );
Description
This filter allows you to dynamically change the current language code in WordPress. It's useful for scenarios where you need to programmatically influence language-specific functionality, such as content retrieval or display, overriding the default language detection. Use it before language-dependent operations.
Usage
add_filter( 'wpml_current_language', 'your_function_name', 10, 1 );
Return Value
The filtered value.
Examples
/**
* Example of how to use the 'wpml_current_language' filter to dynamically set the current language.
* This is useful if you need to temporarily override the globally set language for a specific operation,
* for instance, when programmatically creating or updating content in a different language.
*
* @param string $current_language The current language code, defaults to 'en'.
* @return string The language code to be used for the current operation.
*/
add_filter( 'wpml_current_language', 'my_custom_wpml_current_language', 10, 1 );
function my_custom_wpml_current_language( $current_language ) {
// Check if we are within a specific context where we need to force a language.
// For example, if a specific GET parameter is set, or if we are processing
// a request for a particular type of content.
if ( isset( $_GET['force_lang'] ) && ! empty( $_GET['force_lang'] ) ) {
$forced_language = sanitize_text_field( $_GET['force_lang'] );
// Ensure the forced language is a valid WPML language.
// You might want to fetch a list of available languages from WPML settings.
$available_languages = apply_filters( 'wpml_get_languages', null ); // Assuming this filter exists or you have another way to get them.
$valid_languages = [];
if ( $available_languages ) {
foreach ( $available_languages as $lang_code => $lang_details ) {
$valid_languages[] = $lang_code;
}
} else {
// Fallback to a common set of languages if WPML is not accessible here.
$valid_languages = ['en', 'fr', 'es', 'de'];
}
if ( in_array( $forced_language, $valid_languages ) ) {
return $forced_language;
}
}
// If no specific override is needed, return the language that was passed in.
// This could be the default 'en' or whatever WPML has set globally.
return $current_language;
}
Placement
This code should be placed in the functions.php file of your active theme, a custom plugin, or using a code snippets plugin.
Source Code
src/classes/woocommerce/woocommerce-license.php:1016
src/classes/helpers/shared-functions.php:486
if ( defined( 'ICL_SITEPRESS_VERSION' ) ) {
$type = 'groups';
// Get the translation id (trid)
$trid = 0;
// Set the desired language
$language_code = apply_filters( 'wpml_current_language', 'en' );
// Update the post language info
$language_args = array(
'element_id' => $group_id,
'element_type' => 'post_' . $type,
'trid' => $trid,
'language_code' => $language_code,