How to Translate Theme Options inside Customizer with Polylang and WPML

As I said in my first post here, after months thinking about it, I’ve finally decided to turn this blog multilingual in an attempt to get more clients among Codeable‘s target audience. I had to decide between turning this WordPress installation into a multisite one or using a plugin and, after this twitter thread, I gave Polylang a chance.

I used to work with WPML but as Polylang has a free version, it was my first choice. As the blog theme is a simple one I didn’t face any difficulty, unless how to translate an option I have in Customizer. Are you seeing the Creative Commons license in the footer? Yes, that is a Customizer field, built this way:

function felipeelia_customize_register( $wp_customize ) {
	$wp_customize->add_section(
		'felipeelia_rodape',
		array(
			'title'    => 'Rodapé',
			'priority' => 125,
		)
	);
	$wp_customize->add_setting(
		'copyright',
		array(
			'default'    => '',
			'capability' => 'edit_theme_options',
		)
	);
	$wp_customize->add_control(
		'copyright',
		array(
			'label'    => 'Copyright',
			'section'  => 'felipeelia_rodape',
			'settings' => 'copyright',
			'type'     => 'textarea',
		)
	);
}
add_action( 'customize_register', 'felipeelia_customize_register' );

That code creates a Copyright field in the Rodapé (Footer) Customizer section. To show it I use the following code in my footer.php:

<?php echo get_theme_mod( 'copyright' ); ?>

I needed to translate that and I didn’t know how. Actually, I had a guess, but I didn’t work on anything like that before. A long time ago, WPML created a file pattern called wpml-config.php, that allows plugins and themes to declare which post types, taxonomies, and admin texts should be translated. Theme mods fall in that “admin text” section. As it already was the pattern at that time, Polylang also uses the same file. Yeah, with their competitor’s name.

Everything kept in the wp_options tables fall in the admin text section. Theme mods, these we call with get_theme_mod, are stored in an option called theme_mods_THEMENAME and its value is a serialized associative array, i.e., an array with named keys that passes through PHP serialize function before being saved. At the end of the day, all I had to do was create a file called wpml-config.xml in my theme root directory with the following content:

<wpml-config>
    <admin-texts>
        <key name="theme_mods_felipeelia">
            <key name="copyright" />
        </key>
    </admin-texts>
</wpml-config>

Note that felipeelia, in this case, is my theme slug

If you found this content useful, please share it and leave a comment. That always helps a lot 🙂

Felipe Elia

Associate Director of Platform Engineering na 10up, WordPress Core Contributor, Global Polyglots Mentor na comunidade internacional do WordPress e Locale Manager na comunidade WordPress Brasil.

This Post Has 2 Comments

    1. Felipe Elia

      Thanks for sharing!

Comments are closed.