Use Post Duplicator to Quickly Copy Polylang Posts into Another Language

When building a multilingual site with Polylang, the different language versions of a post often share almost everything except the language itself. Re-entering all of the same custom field data by hand is inefficient, especially when the post contains many custom fields.

To reduce that repeated work, one practical option is to use the Post Duplicator plugin and then automatically connect the duplicated post to the correct Polylang language relationship.

Create the Polylang relationship when the post is duplicated

Post Duplicator provides the mtphr_post_duplicator_created hook, which runs after a new copy is created. Combined with Polylang helper functions, it can be used to assign the duplicate to a target language and connect the two language versions.

add_action('mtphr_post_duplicator_created', function ($original_id, $duplicate_id) {
    $original_id = absint($original_id);
    $original_lang = pll_get_post_language($original_id, 'slug');
    $new_lang = ($original_lang === 'de') ? 'zh' : 'de';

    pll_set_post_language($duplicate_id, $new_lang);

    $translations = pll_get_post_translations($original_id);
    $translations[$new_lang] = $duplicate_id;

    pll_save_post_translations($translations);
}, 10, 2);

In this example, zh is the Polylang slug for Simplified Chinese and de is the slug for German. After the post is duplicated, the code determines the source language, sets the duplicate to the other language, and then saves the translation mapping.

Copy the translated taxonomy terms after duplication

Duplicating the post body and custom fields is only part of the story. The taxonomy terms do not automatically carry over, because the source-language terms and target-language terms are separate records linked through Polylang.

You can use pll_get_term() to find the equivalent translated term in the new language, then assign those translated terms to the duplicated post.

function polylang_set_new_terms($original_id, $duplicate_id, $taxonomy, $new_lang) {
    $terms = wp_get_object_terms($original_id, $taxonomy, array('fields' => 'ids'));
    $new_terms = array();

    foreach ($terms as $term_id) {
        $translated_term_id = pll_get_term($term_id, $new_lang);
        if ($translated_term_id) {
            $new_terms[] = $translated_term_id;
        }
    }

    wp_set_object_terms($duplicate_id, $new_terms, $taxonomy);
}

Call that helper from the duplication hook at the right point and the duplicated post can inherit the corresponding taxonomy terms in the target language as well.

The example above handles two languages. If your site supports more than two, the logic becomes more complex, but the same general strategy still applies.

Related Posts

Leave a Reply

Your email address will not be published. Required fields are marked *