Show a Custom Field From the Right WPML Translation
Adds a [wpide_wpml_field] shortcode that displays a custom field from the current-language version of any post or page, so one shortcode works in every language.
Opens WPIDE on
Code
add_shortcode( 'wpide_wpml_field', function ( $atts ) {
$atts = shortcode_atts( array( 'key' => '', 'id' => 0 ), $atts, 'wpide_wpml_field' );
$key = sanitize_key( $atts['key'] );
$id = $atts['id'] ? absint( $atts['id'] ) : get_the_ID();
if ( '' === $key || ! $id || is_protected_meta( $key, 'post' ) ) {
return '';
}
if ( defined( 'ICL_SITEPRESS_VERSION' ) ) {
$id = (int) apply_filters( 'wpml_object_id', $id, get_post_type( $id ), true );
}
$value = get_post_meta( $id, $key, true );
return is_scalar( $value ) ? wp_kses_post( (string) $value ) : '';
} );
Notes
Use [wpide_wpml_field key="opening_hours" id="42"]; leave out id to use the current post. Falls back to the original post when no translation exists.
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.