How to copy post meta to the remote sites

This code snippet shows how to copy post meta to the remote site(s). In the example it gets the value of yoast_wpseo_title post meta from the request and then updates the value in the connected sites.

add_action('multilingualpress.metabox_after_relate_posts', function($context, $request) {

    // get post meta value from source site
    $yoastWpseoTitleValue = (string)$request->bodyValue(
        'yoast_wpseo_title',
        INPUT_POST,
        FILTER_SANITIZE_SPECIAL_CHARS
    );

    // switch to remote sites and save post meta
    $remoteSiteId = $context->remoteSiteId();
    $remotePostId = $context->remotePostId();
    switch_to_blog($remoteSiteId);
    update_post_meta($remotePostId, '_yoast_wpseo_title', $yoastWpseoTitleValue);
    restore_current_blog();
}, 10, 2);

The above example shows a case when a plugin registers the custom field, but it is also possible to connect custom fields generated by WordPress from Custom Fields UI in post editor, so let say we have created a new custom field my-field in site one and we want to synchronize the value to the same custom field in site 2, once we have created the custom field with the same name in site 2, we can use the multilingualpress.metabox_after_relate_posts action like so:

add_action('multilingualpress.metabox_after_relate_posts', function ($context, $request) {
    // switch to source site
    switch_to_blog($context->sourceSiteId());

    // grab post meta value
    $value = get_post_meta($context->sourcePostId(), 'my-field', true);

    // switch to remote site
    restore_current_blog();

    // update post meta
    update_post_meta($context->remotePostId(), 'my-field', $value);
}, 10, 2);


Build the perfect multilingual webshop with WooCommerce and our plugins MultilingualPress and CentralStock!