Skip to content

Instantly share code, notes, and snippets.

@nico-martin
Last active Apr 15, 2020
Embed
What would you like to do?
A PHP-Class to make fields translatable
add_action( 'acf/init', function() {
acf_add_local_field_group([
'key' => 'myGroup',
'title' => 'Group',
'multilang' => true,
'menu_order' => 50,
'fields' => [
[
'key' => 'field_myField',
'name' => 'myField',
'label' => 'my field',
'type' => 'text',
],
],
'location' => [
[
[
'param' => 'options_page',
'operator' => '==',
'value' => 'myPage',
],
],
],
]);
} );
<?php
namespace SayHello\Theme\Package;
/**
* @author Nico Martin <nico@sayhello.ch>
*/
class Polylang
{
public $translatedNames = [];
public function run()
{
if ( ! function_exists('pll_current_language')) {
return;
}
add_filter('acf/validate_field_group', [$this, 'multilangGroup']);
add_filter('acf/load_value', [$this, 'multilangField'], 20, 3);
add_filter('acf/load_reference', [$this, 'manipulateNameReference'], 20, 2);
}
public function multilangGroup($group)
{
if ( ! array_key_exists('multilang', $group) || $group['multilang'] !== true) {
return $group;
}
$fields = $group['fields'];
$newFields = [];
foreach (self::languages() as $key => $name) {
$newFields[] = [
'key' => $group['key'] . '-langtab-' . $key,
'name' => $group['key'] . '-langtab-' . $key,
'label' => $name,
'type' => 'tab',
];
foreach ($fields as $field) {
acf_get_local_store('fields')->set($field['name'], $field);
$this->translatedNames[$field['name']] = $field['name'] . '-polylang-' . pll_current_language();
$field['key'] = $field['key'] . '-polylang-' . $key;
$field['name'] = $field['name'] . '-polylang-' . $key;
$newFields[] = $field;
}
}
$group['fields'] = $newFields;
return $group;
}
public function multilangField($value, $post_id, $field)
{
if (is_admin() || $value) {
return $value;
}
$newKey = $field['key'] . '-polylang-' . pll_current_language();
if (acf_maybe_get_field($newKey, $post_id)) {
return get_field($newKey, $post_id, false);
}
return $value;
}
public function manipulateNameReference($reference, $field_name)
{
if ($reference === null && is_string($field_name) && array_key_exists($field_name, $this->translatedNames)) {
return $this->translatedNames[$field_name];
}
return $reference;
}
public static function languages()
{
if ( ! function_exists('pll_the_languages')) {
return [explode('_', get_locale())[0]];
}
$langs = get_terms('term_language', [
'hide_empty' => false,
]);
$return = [];
foreach ($langs as $lang) {
$key = str_replace('pll_', '', $lang->slug);
$return[$key] = $lang->name;
}
return $return;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment