Halloween Sale 15% off Ends in See the plans
PHP

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.

Don’t have WPIDE yet? Install it on your site

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

  1. Install WPIDE on your WordPress site (it is free) and open Code Snippets.
  2. Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
  3. It is added inactive: review the code and settings, then switch it on.

Have a snippet worth sharing?

Publish it to the library from WPIDE or right here. Sign in with any WordPress site that runs WPIDE, free or Pro. Public snippets are reviewed by the WPIDE team before they appear.

Which site should get this snippet?

Enter the address of your WordPress site. WPIDE opens there in a new tab with the snippet ready to review and save.

Remembered in this browser only, so you are asked once.

Report this snippet

Tell the WPIDE team what is wrong: broken code, something harmful, spam or copied work.