[Plugin WPML] : How to create a translation of a post using the WPML API?

The question:

I’m trying to figure out how to create a translation for a post using the internal WPML API (inc/wpml-api.php)

I simply want to create a translation for post ID xx, set some content and publish it.

I’ve tried to play around with wpml_add_translatable_content but couldn’t get it right. Unfortunately there is not much documentation available for this. The closest lead I found is this thread, but I couldn’t reduce the code to what I need. It’s also possible to do this by directly writing to the database, following WPML’s table structure, but I want to use the API.

Any suggestions are welcome.

The Solutions:

Below are the methods you can try. The first solution is probably the best. Try others if the first one doesn’t work. Senior developers aren’t just copying/pasting – they read the methods carefully & apply them wisely to each case.

Method 1

I came up with a function that does the job for now :

/**
 * Creates a translation of a post (to be used with WPML)
 *  
 * @param int $post_id The ID of the post to be translated.
 * @param string $post_type The post type of the post to be transaled (ie. 'post', 'page', 'custom type', etc.).
 * @param string $lang The language of the translated post (ie 'fr', 'de', etc.).
 *    
 * @return the translated post ID
 *  */
function mwm_wpml_translate_post( $post_id, $post_type, $lang ){

    // Include WPML API
    include_once( WP_PLUGIN_DIR . '/sitepress-multilingual-cms/inc/wpml-api.php' );

    // Define title of translated post
    $post_translated_title = get_post( $post_id )->post_title . ' (' . $lang . ')';

    // Insert translated post
    $post_translated_id = wp_insert_post( array( 'post_title' => $post_translated_title, 'post_type' => $post_type ) );

    // Get trid of original post
    $trid = wpml_get_content_trid( 'post_' . $post_type, $post_id );

    // Get default language
    $default_lang = wpml_get_default_language();

    // Associate original post and translated post
    global $wpdb;
    $wpdb->update( 
        $wpdb->prefix.'icl_translations', 
        array( 
            'trid' => $trid, 
            'language_code' => $lang, 
            'source_language_code' => $default_lang 
        ), 
        array( 
            'element_type' => $post_type, 
            'element_id' => $post_translated_id 
        ) 
    );

    // Return translated post ID
    return $post_translated_id;

}


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Comment