Make Any Text Option Translatable With WPML
Registers the text of selected site options, for example a plugin's notice text or a cookie banner message, in WPML String Translation and returns the right translation on the front end.
Opens WPIDE on
Code
$wpide_options = array( 'my_plugin_notice_text' ); // Option names holding plain text.
add_action( 'admin_init', function () use ( $wpide_options ) {
if ( ! defined( 'ICL_SITEPRESS_VERSION' ) ) {
return;
}
foreach ( $wpide_options as $option ) {
$value = get_option( $option );
$hash = md5( (string) maybe_serialize( $value ) );
if ( is_string( $value ) && '' !== $value && get_option( 'wpide_wpml_opt_' . $option ) !== $hash ) {
do_action( 'wpml_register_single_string', 'Site options', $option, $value );
update_option( 'wpide_wpml_opt_' . $option, $hash, false );
}
}
} );
if ( ! is_admin() ) {
foreach ( $wpide_options as $wpide_option ) {
add_filter( 'option_' . $wpide_option, function ( $value ) use ( $wpide_option ) {
return is_string( $value ) && '' !== $value
? apply_filters( 'wpml_translate_single_string', $value, 'Site options', $wpide_option )
: $value;
} );
}
}
Notes
Only works for options stored as plain strings. For array options, use WPML's own Admin Texts screen instead.
How to add this snippet
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.