Get the original language post ID for WPML-translated posts

Problem:

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 language.

Solution

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

where #myid# is the ID of your current (possibly translated) post.

The algorithm works like this:

  1. Find out the  translation ID (column trid) for the current post by selecting the row for the given post ID (column element_id)
  2. Find all rows with the same translation ID
  3. 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 $orig_lang_id is 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 wp_icl_translations table.

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.