Skip to content

Instantly share code, notes, and snippets.

@djoo
Last active March 4, 2024 17:26
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save djoo/5518bcf4ccef93ab83d91787c41e929a to your computer and use it in GitHub Desktop.
Save djoo/5518bcf4ccef93ab83d91787c41e929a to your computer and use it in GitHub Desktop.
WPML Custom end point link 2 existing translation
<?php
/**
* Link the FR translation and the EN translation
* Called by API https://domain.com/wp-json/link_translation/post/
*/
function custom_rest_link_translation($data) {
//Source https://wpml.org/wpml-hook/wpml_set_element_language_details/
$inserted_post_ids = array(
'original' => $data['original'],
'translation' => $data['translation']
);
if ( $inserted_post_ids) {
// https://wpml.org/wpml-hook/wpml_element_type/
$wpml_element_type = apply_filters( 'wpml_element_type', 'post' );
// get the language info of the original post
// https://wpml.org/wpml-hook/wpml_element_language_details/
$get_language_args = array('element_id' => $inserted_post_ids['original'], 'element_type' => 'post' );
$original_post_language_info = apply_filters( 'wpml_element_language_details', null, $get_language_args );
$set_language_args = array(
'element_id' => $inserted_post_ids['translation'],
'element_type' => $wpml_element_type,
'trid' => $original_post_language_info->trid,
'language_code' => 'en',
'source_language_code' => $original_post_language_info->language_code,
'check_duplicates' => true
);
$value = do_action( 'wpml_set_element_language_details', $set_language_args );
echo "linked";
}
}
add_action('rest_api_init', function () {
register_rest_route('link_translation', '/post', array(
'methods' => 'POST',
'callback' => 'custom_rest_link_translation',
));
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment