我想在Wordpress的functions.php中使用Polylang自动进行语言(英语和法语)之间的翻译。我的意思是当用户在英文页面上创建/发布/更新自定义帖子类型帖子时, 法语页面也应该自动创建和发布,法语页面也是如此。
我有一个名为“宝石小册子”的自定义帖子类型。
我尝试了以下代码,但没有成功:
function auto_translate($post_id, $post, $update)
{
if (!$update) {
return;
}
// prevent creation of additional duplicate draft posts
if ( $post->post_status == 'draft' ){
return;
}
// prevent recursion when publishing translations
remove_action('save_post', 'auto_translate', 999, 3);
global $wp_query, $post, $polylang;
$langs = ['en', 'fr'];
$args = array( 'post_type' => 'gem-booklets');
$loop = new WP_Query( $args );
while ( $loop->have_posts() ) : // $loop->the_post();
$p_id = $post->ID;
endwhile;
$current_translations = pll_get_post_translations($p_id);
$post_type = get_post_type($p_id);
if ($post_type == 'gem-booklets') {
foreach ($langs as $lang) {
if (!isset($current_translations[$lang])) {
$polylang->sync_post_model->copy_post($p_id, $lang, true);
}
}
}
}
// needs low priority or the synchronisation option wont be saved
add_action('save_post', 'auto_translate', 999, 3);
我从这篇原始文章中编辑了上述代码:
您能告诉我如何解决这个问题吗?
更新:
我已经尝试了以下代码,这一行不再有错误 $polylang->sync_post_model->copy_post($post_id, $lang, true);但发布新帖子时不会自动创建任何内容或翻译:
function auto_translate($post_id, $post, $update)
{
if (!$update) {
return;
}
// prevent creation of additional duplicate draft posts
if ( $post->post_status == 'draft' ){
return;
}
// prevent recursion when publishing translations
remove_action('save_post', 'auto_translate', 999, 3);
global $polylang;
$langs = ['en', 'km'];
$current_translations = pll_get_post_translations($post_id);
$post_type = get_post_type($post_id);
if ($post_type == 'gem-booklets') {
foreach ($langs as $lang) {
if (!isset($current_translations[$lang])) {
if ( have_posts() ) {
while ( have_posts() ) :
// the_post();
$polylang->sync_post_model->copy_post($post_id, $lang, true);
endwhile;
}
}
}
}
}
// needs low priority or the synchronisation option wont be saved
add_action('save_post', 'auto_translate', 999, 3);
如有任何建议,我们将不胜感激。