Last active
May 18, 2016 13:31
-
-
Save jonathan-dejong/26ec2bf8bf25890c2365 to your computer and use it in GitHub Desktop.
Automatically fetch current language meta value for user fields with ACF
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* Modify ACF fields to account for translations if available | |
* | |
* This solution requires the use of Polylang for WP translations. | |
* Use this by duplicating the field groups for user meta and append _languageslug to each field in the duplicated group. | |
* So for a site with a swedish translation an example field would be named "user_phonenumber" | |
* in english (default) and in the swedish translation group "user_phonenumber_sv" | |
*/ | |
function load_translated_value_if_exists( $value, $post_id, $field ){ | |
//dont modify admin | |
if( is_admin() || !function_exists('pll_current_language') ) | |
return $value; | |
//Current language slug from polylang | |
$current_lang = pll_current_language('slug'); | |
$translated_value = false; | |
if ( strpos($post_id, 'user') !== false ) { | |
//User meta | |
$user_id = explode('_', $post_id)[1]; | |
if( strpos($field['parent'], 'field') !== false ){ | |
//this is a subfield so we need to modify the parent field section of it's name too. | |
preg_match('/_\d+_/', $field['name'], $match); | |
//rebuild it | |
$components = explode($match[0], $field['name']); | |
$fieldname = $components[0] . '_' . $current_lang . $match[0] . $components[1] . '_' . $current_lang; | |
}else{ | |
$fieldname = $field['name'] . '_' . $current_lang; | |
} | |
$translated_value = get_user_meta($user_id, $fieldname, true); | |
} | |
if( $translated_value ) | |
return $translated_value; | |
return $value; | |
} | |
add_filter('acf/load_value', 'load_translated_value_if_exists', 10, 3); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment