polylang translation of a custom post created by wp_insert_post()
-
15-04-2021 - |
문제
I am in trouble. I have a travel site...I have created a page where users can write a form to insert their houses.
The houses are of course a custom post type.
This is a piece of my code:
...
some validation here
if ($idarticolo = wp_insert_post($post)) {
//lingua
global $polylang;
$lang = pll_current_language();
$polylang->set_post_language($idarticolo, $lang);
...
everything works fine, the house is inserted in my current language; but when I try to translate this post from admin panel, I get an error.
The post is not translated, and no language is detected.
Please help!!!...many thanks in advance!
M.:)
해결책
Apparently Polylang has an undocumented pll_save_post API method. See here: https://wordpress.org/support/topic/programmatically-set-post-language-and-translations
다른 팁
Ok Riaan,
thank you for your reply.
I solved in this way (maybe can be helpful):
if ($idarticolo = wp_insert_post($post, true)) {
// inserisco l'articolo nelle altre lingue: En Es Fr
$idarticoloEn = wp_insert_post($post, true);
$idarticoloEs = wp_insert_post($post, true);
$idarticoloFr = wp_insert_post($post, true);
$polylang->model->set_post_language($idarticolo, 'it');
$polylang->model->set_post_language($idarticoloEn, 'en');
$polylang->model->set_post_language($idarticoloEs, 'es');
$polylang->model->set_post_language($idarticoloFr, 'fr');
$polylang->model->save_translations('post', $idarticolo, array('en' => $idarticoloEn));
$polylang->model->save_translations('post', $idarticolo, array('es' => $idarticoloEs));
$polylang->model->save_translations('post', $idarticolo, array('fr' => $idarticoloFr));
I insert the post in italian, and then I create the corresponding translations in the the other languages.
Thank you again for your help!
M :)
Update @Mauro's answer based Polylang version 2.5.3.
....
if ($idarticolo = wp_insert_post($post, true)) {
$posts = array(
'en' => '',
'es' => '',
'fr' => '',
);
// inserisco l'articolo nelle altre lingue: En Es Fr
foreach ($posts as $language => $value) {
$posts[$language] = wp_insert_post($post, true);
}
if (function_exists('pll_set_post_language')
&& function_exists('pll_save_post_translations')) {
pll_set_post_language($idarticolo, 'it');
foreach ($posts as $language => $value) {
pll_set_post_language($value, $language);
}
pll_save_post_translations(array_merge(array($idarticolo), $posts));
}
....
To set term language, use pll_set_term_language
.
To save term translations, use pll_save_term_translations
.