WPML
SignaturePHP
apply_filters( 'wpml_copy_post_to_language', int $post_id, string $target_language, bool $mark_as_duplicate )

Description

This filter hook allows developers to copy a post to a specified language with WPML. It duplicates the post into the target language and provides the option to mark it as a duplicate or as a translation.

Arguments

  • $post_idintRequired

    The ID of the post to be copied.
  • $target_languagestringRequired

    The language code of the target language to which the post will be copied.
  • $mark_as_duplicateboolRequired

    If set to true, the duplicated post will be marked as a duplicate of the original post. If false, it will be treated as a translated post.

Example Usage

In the example below, we use the filter to copy a post with the ID of 1 into French and mark it as a duplicate of the original post.

PHP
$duplicate_post_id = apply_filters( 'wpml_copy_post_to_language', 1, 'fr', true );

In the advanced example you see below, we demonstrate how to automatically duplicate a given post to all other active languages on your WPML site, excluding the original language of the post.

Advanced examplePHP
function myplugin_duplicate_copy_post_to_secondary_languages( $post_id, $mark_as_duplicate = false ) {
    // Retrieve the post's element type, trid, and existing translations
    $element_type = apply_filters( 'wpml_element_type', get_post_type( $post_id ) );
    $trid         = apply_filters( 'wpml_element_trid', null, $post_id, $element_type );
    $translations = (array) apply_filters( 'wpml_get_element_translations', [], $trid, $element_type );

    if ( ! $translations ) {
        // Handle error or invalid values accordingly
        return;
    }

    // Retrieve the active languages
    $wpml_languages = (array) apply_filters('wpml_active_languages', [], 'orderby=id&order=desc');

    foreach ( $wpml_languages as $language ) {
        // Duplicate the post if no translation exists for the given language
        if ( ! isset( $translations[ $language['language_code'] ] ) ) {
            apply_filters(
                    'wpml_copy_post_to_language',
                    $post_id,
                    $language['language_code'],
                    $mark_as_duplicate
            );
        }
    }
}