apply_filters( 'wpml_copy_post_to_language', int $post_id, string $target_language, bool $mark_as_duplicate )
- Type
- filter
- Category
- Inserting Content
- WPML Version
- 4.0.0
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
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.
Example
$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 example
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
);
}
}
}
Related hooks
wpml_set_element_language_details, wpml_make_post_duplicates, wpml_admin_make_post_duplicates, wpml_delete_package, wpml_import_get_trid_from_imported_translations, wpml_register_string, wpml_register_single_string, wpml_show_package_language_ui, wpml_delete_package_action