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.
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.
Manage Cookie Consent
We use cookies to optimize our website and services. Your consent allows us to process data such as browsing behavior. Not consenting may affect some features.
Functional
Always active
Required for our website to operate and communicate correctly.
Preferences
The technical storage or access is necessary for the legitimate purpose of storing preferences that are not requested by the subscriber or user.
Statistics
We use these to analyze the statistics of our site. Collected information is completely anonymous.The technical storage or access that is used exclusively for anonymous statistical purposes. Without a subpoena, voluntary compliance on the part of your Internet Service Provider, or additional records from a third party, information stored or retrieved for this purpose alone cannot usually be used to identify you.
Marketing
These cookies track your browsing to provide ads relevant to you.