You have a post that has been translated into multiple languages using WPML.
You want to find out the ID of the original post, i.e. the equivalent post in the source langugae.
As far as I know, there is no WPML API for this. You can, however, use
$wpdb in order to query the database directly.
Here’s the SQL statement:
SELECT trans2.element_id FROM wp_icl_translations AS trans1 INNER JOIN wp_icl_translations AS trans2 ON trans2.trid = trans1.trid WHERE trans1.element_id = #myid# AND trans2.source_language_code IS NULLs
#myid# is the ID of your current (possibly translated) post.
The algorithm works like this:
- Find out the translation ID (column
trid) for the current post by selecting the row for the given post ID (column
- Find all rows with the same translation ID
- Select only the row where the source language is
NULL– this is the original post.
You can use it like this:
global $wpdb; $orig_lang_id = $wpdb->get_var("SELECT trans2.element_id FROM wp_icl_translations AS trans1 INNER JOIN wp_icl_translations AS trans2 ON trans2.trid = trans1.trid WHERE trans1.element_id = ".get_the_ID()." AND trans2.source_language_code IS NULL");
and then use
$orig_lang_id where required. Note that
NULL if the query fails. The main reason for the query to fail is if there is no entry for the given post ID in the
If the current post is the source post,
$orig_lang_id is the same as
get_the_ID(), i.e. the current ID of the post.
In my test, the code still works (i.e. returns the correct post ID) even when creating brand-new entry without any translations being present.