我正在使用Wordpress 4.6,WPML 3.5,WooCommerce Multilingual 3.8.6和WooCommerce版本2.6.4开发一个WooCommerce多语言商店。
代码始终返回主要语言的类别,但从不返回指定语言的翻译。
以下是代码: -
private $lang;
function __construct($lang = "en") {
$this->lang = $lang;
}
private function getCategories() {
try {
$api = WC()->api->WC_API_Products;
$categories = $api->get_product_categories();
$products_categories = $categories["product_categories"];
foreach($products_categories as $category) {
$id = absint($category["id"]);
$category["name"] = $this->get_translated_term_name($id, "product_cat", $this->lang);
}
return $products_categories;
} catch (Exception $e) {
error_log("Caught $e");
}
}
private function get_translated_term_name($term_id, $taxonomy, $language) {
$translated_term_id = icl_object_id($term_id, $taxonomy, true, $language);
$translated_term_object = get_term_by('id', $translated_term_id, $taxonomy);
return $translated_term_object->name;
}
答案 0 :(得分:0)
<?php
function wpa89819_wc_single_product(){
$product_cats = wp_get_post_terms( get_the_ID(), 'product_cat' );
if ( $product_cats && ! is_wp_error ( $product_cats ) ){
$single_cat = array_shift( $product_cats ); ?>
<h2 itemprop="name" class="product_category_title"><span><?php echo $single_cat->name; ?></span></h2>
<?php }
}
add_action( 'woocommerce_single_product_summary', 'wpa89819_wc_single_product', 2 );
答案 1 :(得分:0)
我在此链接中找到了解决方案:
https://wpml.org/forums/topic/how-to-get-the-translated-taxonomy-object/
原来,WPML自动调整了分类法的ID,所以在调用get_term之前删除过滤器解决了问题,这里是代码:
private function get_translated_term_name($term_id, $taxonomy, $language) {
global $sitepress;
remove_filter('get_term', array($sitepress,'get_term_adjust_id'), 1, 1);
$translated_term_id = icl_object_id($term_id, $taxonomy, true, $language);
$translated_term_object = get_term($translated_term_id, $taxonomy);
add_filter('get_term', array($sitepress,'get_term_adjust_id'), 1, 1);
return $translated_term_object->name;
}
答案 2 :(得分:0)
此外,您可能会对get_term支持函数的行为感到惊讶。有时它不会将与提供的term_id相对应的术语作为输入参数返回,而是返回缓存结果!所以我以这种方式重写它以绕过这个。
private function getTerm($id) {
global $wpdb;
$id = absint($id);
if(!$id) {
return false;
}
$term = $wpdb->get_results("SELECT * FROM $wpdb->terms WHERE term_id=$id");
return $term;
}