Skip to content

Instantly share code, notes, and snippets.

@jonathan-dejong
Last active May 18, 2016 13:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jonathan-dejong/26ec2bf8bf25890c2365 to your computer and use it in GitHub Desktop.
Save jonathan-dejong/26ec2bf8bf25890c2365 to your computer and use it in GitHub Desktop.
Automatically fetch current language meta value for user fields with ACF
/*
* 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