Skip Navigation

This is the technical support forum for WPML - the multilingual WordPress plugin.

Everyone can read, but only WPML clients can post here. WPML team is replying on the forum 6 days per week, 22 hours per day.

This topic contains 1 reply, has 2 voices.

Last updated by Bruno 4 years, 7 months ago.

Assisted by: Bruno.

Author Posts
June 29, 2020 at 8:56 pm #6480151

massimilianoB-15

Hi, I have a site with 5 languages, the default one is English. I'm writing a migration script from another CMS, and I need to create posts only in a secondary language (i.e. Spanish). I can do it using the admin interface, but not using WPML Api.

When I create a new post using wp_insert_post, it is created in English, but I cannot change its language. I've tried with the wpml_set_element_language_details action, as in the snippet below, but it doesn't work. I've also tried to set the current language before inserting the post, but without success.

Can you help me? Thanks!

//

$trid = wpml_get_content_trid( 'post_' . $type, $post_id );
$language_args = [
'element_id' => $post_id,
'element_type' => 'post_'.$type,
'trid' => $trid,
'language_code' => $language_code,
'source_language_code' => null,
];

do_action( 'wpml_set_element_language_details', $language_args );

June 30, 2020 at 3:57 am #6481661

Bruno

Hello,

Thank you for contacting us. I was unable to replicate the problem you are reporting. I tested this code:

add_action( 'template_redirect', function() {

	if( is_admin() ) {
		return false;
	}

	// Create post on the default language
	$create_post = array(
		'post_title'    => wp_strip_all_tags( "Hello World API" ),
		'post_content'  => "Some content here!",
		'post_status'   => 'publish',
		'post_author'   => 1,
		'post_category' => array( 1 )
	);
 
	// Insert the post into the database and return the post id
	$post_id = wp_insert_post( $create_post );

        // Get the post type
	$type = get_post_type( $post_id );

	// Get the translation id (trid)
	$trid = wpml_get_content_trid( 'post_' . $type, $post_id );
	
	// Set the desired language
	$language_code = 'fr';

	// Update the post language info
	$language_args = [
		'element_id' => $post_id,
		'element_type' => 'post_'.$type,
		'trid' => $trid,
		'language_code' => $language_code,
		'source_language_code' => null,
	];

	do_action( 'wpml_set_element_language_details', $language_args );
});

The code above creates the post in the original language and then updates the language information, making the post to be displayed only in the correct language.

Please, let me know if I can help with any other questions you may have about it. I'll be happy to help.

Thank you.