Adding WPML Taxonomy Translations Via Code

This is really obscure, but hopefully helpful to someone.

When you are using WordPress, this enables you to add a translation for an existing taxonomy term and associate it with the original. For example, when you are using WPML and creating posts via the WordPress API from an XML feed or similar.

So basically you pass in the details of your new term, the taxonomy name, the ISO language code you are targeting and the ID of the existing taxonomy. I lifted this from an existing sample, but  amended it so the slug was unique (I was lazy and just add the language code to the original), and also fixed an issue where the correct id wasn’t being returned.


/* MT 2015-10-29 Enables Categories to be Programatically Added
    (str) $term is the text of the term you want to add.
    (str) $taxonomy is the name of your custom taxonomy.
    (str) $language_code is the two letter code of the language you want to save the term in.
    (int) $content_id is the ID of the term in the default language to associate with the new term.
    @ returns (bool) false on error or if term exists. (int) 0 for no affected rows and term object on success.
function wpml_insert_term($term, $taxonomy, $language_code, $content_id) {
    $slug = "";
    $old_term = get_term( $content_id, $taxonomy );
    $slug = $old_term->slug . '-' . $language_code;
    $new_term = false;
    //if(!term_exists($term, $taxonomy) && taxonomy_exists($taxonomy)){
        $new_term = wp_insert_term($term, $taxonomy,array('slug' => $slug));
            // Include WPML API
            include_once( WP_PLUGIN_DIR.'/sitepress-multilingual-cms/inc/wpml-api.php' );

            global $wpdb;
            $update = $wpdb->update( 
                array( // data
                    'trid' => wpml_get_content_trid( 'tax_'.$taxonomy, $content_id), 
                    'element_type' => 'tax_'.$taxonomy, 
                    'language_code' => $language_code, 
                    'source_language_code' => wpml_get_default_language()
                array( // where
                    'element_id' => $new_term['term_id'],
                    'element_type' => 'tax_'.$taxonomy
            $new_term = ($update === false || $update === 0) ? $update : $new_term;
    return $new_term;