While migrating a multilingual website to WordPress, WPML comes in handy. It is a plugin known for maintaining multilingual websites in WordPress.
This post contains my notes about how I tackled this problem while working on a migration project.
WPML API Hooks
WPML enables you to link the migrated multilingual posts with each other in WordPress using its internal API hooks. There are three plugin hooks that are required for this process.
wpml_element_type— Filter hook
wpml_element_language_details— Filter hook
wpml_set_element_language_details— Action hook
WPML maintains element types against each data type present in WordPress like post, custom post type, or custom taxonomy, etc. This filter hook is used to get the element type name from the plugin.
The filter hook accepts the key of the data type as argument, for example, comment, post, page, attachment, etc. And it returns the WPML element type as a result.
// $wpml_element_type will return 'post_post' $wpml_element_type = apply_filters( 'wpml_element_type', 'post' );
This filter hook is used to get the language details of a post. It returns the details of the data type, e.g. a post, in an array, which can be used to set the translated post of a parent post using wpml_set_element_language_details hook.
The hook accepts two arguments, a WordPress object and an array containing the data id and the data type key. For example, you can use the following code to get the language details of a post present in WordPress.
// Get WPML language details for a post using post id. $my_post_language_info = apply_filters( 'wpml_element_language_details', null, [ 'element_id' => <WordPress-Post-ID>, 'element_type' => 'post', ] );
The first argument is by default null. The second argument contains the information about the data type that you want to get from WPML. The data type can be a post, page, attachment, nav_menu_item, custom-post-key, category, post_tag, nav_menu, custom-taxonomy-key, etc.
The two most important pieces of information that we get from this hook are the translation id — trid — and the language code of a post.
Simply put, this hook adds a translated post to a parent post. For example, your parent post is in English. And you have to link the French translation of the post to this parent post.
You will use the parent post to get the language details — as explained in the section above — and then you will use wpml_set_element_language_details to set the English post as parent post of the French post.
// Set translation post details for WPML. do_action( 'wpml_set_element_language_details', [ 'element_id' => <translation-post-id>, 'element_type' => apply_filters( 'wpml_element_type', 'post' ), 'trid' => <translation-id or trid>, 'language_code' => <translated-post-language-code>, 'source_language_code' => <parent-post-language-code>, ] );
WPML uses the translation-id or trid of the parent post to link the posts with each other.
That’s about it.