- availability:
-
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.
- type:
- filter
- category:
- Inserting Content
- parameters:
-
apply_filters( 'wpml_copy_post_to_language', int $post_id, string $target_language, bool $mark_as_duplicate )
- $post_id
- (int) (Required) The ID of the post to be copied.
- $target_language
- (string) (Required) The language code of the target language to which the post will be copied.
- $mark_as_duplicate
- (bool) (Required) 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.
- hook 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
1$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
1234567891011121314151617181920212223242526function
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
);
}
}
}