When translating with WPML custom fields created by the ACF plugin, the question arises – how to make all fields translatable? Usually on the site there are quite a lot of such fields (hundreds – a typical example) and to click in the WPML settings hundreds of times – quite tedious work.
Below is an example of how to do this with the code.
Create an acf-helper
folder at the root of the site. Put two files into it: acf-helper.php
and class-acf-helper.php
.
Code in acf-helper.php
:
<?php
require_once '../wp-load.php';
require_once 'class-acf-helper.php';
$acf_helper = new ACF_Helper();
$acf_helper->make_all_cf_translatable();
Code in class-acf-helper.php
:
<?php
/**
* ACF_Helper class file
*/
/**
* Class ACF_Helper
*/
class ACF_Helper {
private $tm = null;
public function __construct() {
if ( class_exists( 'SitePress' ) ) {
$this->tm = wpml_load_core_tm();
}
}
public function make_all_cf_translatable() {
if ( null === $this->tm ) {
echo 'Error: WPML Multilingual CMS plugin must be activated.';
return;
}
$settings = $this->tm->get_settings();
$factory = new WPML_Custom_Field_Setting_Query_Factory();
$query = $factory->create( WPML_Custom_Field_Setting_Query_Factory::TYPE_POSTMETA );
$cft = $query->get( [ 'hide_system_fields' => true ] );
$cft = array_fill_keys( $cft, WPML_TRANSLATE_CUSTOM_FIELD );
$settings[ WPML_POST_META_SETTING_INDEX_PLURAL ] = array_merge(
$settings[ WPML_POST_META_SETTING_INDEX_PLURAL ],
$cft
);
$this->tm->settings = $settings;
$this->tm->save_settings();
}
}
Start acf-helper.php
and all user field will become translatable.