Copy Custom Fields to All WPML Translations on Save
Copies the custom fields you list from an original post to all of its WPML translations whenever the original is saved, for values like prices, SKUs or coordinates that never change between languages.
Opens WPIDE on
Code
$wpide_keys = array( 'price', 'sku', 'latitude', 'longitude' ); // Meta keys to copy.
add_action( 'save_post', function ( $post_id, $post ) use ( $wpide_keys ) {
static $running = false;
if ( $running || ! defined( 'ICL_SITEPRESS_VERSION' ) || wp_is_post_revision( $post_id ) || wp_is_post_autosave( $post_id ) || ! current_user_can( 'edit_post', $post_id ) ) {
return;
}
$type = apply_filters( 'wpml_element_type', $post->post_type );
$details = apply_filters( 'wpml_element_language_details', null, array( 'element_id' => $post_id, 'element_type' => $type ) );
if ( ! $details || ! empty( $details->source_language_code ) || empty( $details->trid ) ) {
return; // Not an original post.
}
$translations = apply_filters( 'wpml_get_element_translations', null, $details->trid, $type );
if ( empty( $translations ) || ! is_array( $translations ) ) {
return;
}
$running = true;
foreach ( $translations as $translation ) {
$target = (int) $translation->element_id;
if ( $target === (int) $post_id ) {
continue;
}
foreach ( $wpide_keys as $key ) {
if ( metadata_exists( 'post', $post_id, $key ) ) {
update_post_meta( $target, $key, get_post_meta( $post_id, $key, true ) );
} else {
delete_post_meta( $target, $key );
}
}
}
$running = false;
}, 20, 2 );
Notes
Only runs when saving the original (source-language) post. For fields WPML already manages, set them to "Copy" in WPML > Settings > Custom Fields Translation 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.