我正在尝试弄清楚如何使用内部 WPML API(inc/wpml-api.php
)
我只是想为帖子 ID xx 创建一个翻译,设置一些内容并发布。
我试过玩 wpml_add_translatable_content
但做不对。 不幸的是,没有太多的文档可用于此。 我找到的最接近的线索是这个线程,但我无法将代码减少到我需要的。 也可以按照 WPML 的表结构直接写入数据库来完成此操作,但我想使用 API。
欢迎提出任何建议。
我想出了一个暂时可以完成这项工作的功能:
/**
* Creates a translation of a post (to be used with WPML)
*
* @param int $post_id The ID of the post to be translated.
* @param string $post_type The post type of the post to be transaled (ie. 'post', 'page', 'custom type', etc.).
* @param string $lang The language of the translated post (ie 'fr', 'de', etc.).
*
* @return the translated post ID
* */
function mwm_wpml_translate_post( $post_id, $post_type, $lang ){
// Include WPML API
include_once( WP_PLUGIN_DIR . '/sitepress-multilingual-cms/inc/wpml-api.php' );
// Define title of translated post
$post_translated_title = get_post( $post_id )->post_title . ' (' . $lang . ')';
// Insert translated post
$post_translated_id = wp_insert_post( array( 'post_title' => $post_translated_title, 'post_type' => $post_type ) );
// Get trid of original post
$trid = wpml_get_content_trid( 'post_' . $post_type, $post_id );
// Get default language
$default_lang = wpml_get_default_language();
// Associate original post and translated post
global $wpdb;
$wpdb->update(
$wpdb->prefix.'icl_translations',
array(
'trid' => $trid,
'language_code' => $lang,
'source_language_code' => $default_lang
),
array(
'element_type' => $post_type,
'element_id' => $post_translated_id
)
);
// Return translated post ID
return $post_translated_id;
}
答案仍然很好,但是如果您遇到此错误 Call to undefined function wpml_get_content_trid()
替换这个:
// Get trid of original post
$trid = wpml_get_content_trid( 'post_' . $post_type, $post_id );
有了这个 :
// Get trid of original post
$trid = apply_filters( 'wpml_element_trid', NULL, $post_id, 'post_' . $post_type );
WPML 文档:https://wpml.org/wpml-hook/wpml_element_trid/
我没有找到任何文档 wpml_get_content_trid()
功能。 我真的不知道这个函数是否在 WPML 更新中被删除,或者我的代码中是否缺少某些东西。