我正在编写插件但无法获得正确的变体标题 在Woocommerce中,我使用的变体被称为"展开层压"。但是当我试图得到一个变体的标题时我得到了:"图表的变化#781"
这是代码使用:
foreach ($order->get_items() as $item) {
$product_variation_id = $item['variation_id'];
if ($product_variation_id)
{
$product = new WC_Product($product_variation_id);
$productname = get_item_variations($product_variation_id);
}
else
{
$product = new WC_Product($item['product_id']);
$productname = get_the_title($item['product_id']);
}
}
如何获得正确的标题?
答案 0 :(得分:2)
我实际上是在试图解决这个问题,这是我的解决方案,因为变体标题正在返回一个slug。
在WC 2.4.13上测试
$variation = new WC_Product_Variation($variation_id);
$title_slug = current($variation->get_variation_attributes());
$results = $wpdb->get_results("SELECT * FROM wp_terms WHERE slug = '{$title_slug}'", ARRAY_A);
$variation_title = $results[0]['name'];
答案 1 :(得分:1)
我偶然发现了这个'快速'修复。因为没有人发布了我认为会回答的答案。
我刚使用WordPress get_post_meta
来抓取attribute_options
。这是存储所有选项标题的地方(变体标题是产品选项)。
$product_options = get_post_meta($item['variation_id'], 'attribute_options');
将返回一个数组
[attribute_options] => Array
(
[0] => Some Variation Title
)
答案 2 :(得分:1)
以下是使用 WooCommerce 3.2.6
测试此问题的解决方案//Loop through each item from the cart
foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item ) {
//get the current product ID
$product_id = $cart_item['product_id'];
//first - check if product has variations
if(isset($cart_item['variation']) && count($cart_item['variation']) > 0 ){
//get the WooCommerce Product object by product ID
$current_product = new WC_Product_Variable($product_id);
//get the variations of this product
$variations = $current_product->get_available_variations();
//Loop through each variation to get its title
foreach($variations as $index => $data){
get_the_title($data['variation_id']);
}
}
}
答案 3 :(得分:0)
在此函数中,返回输入变体的标题,您可以将定界符','更改为空格或任何需要的内容。
function get_variation_title($variation) {
$str_name = '';
$arr_attributes = $variation -> get_variation_attributes(FALSE);
if (is_array($arr_attributes)) {
foreach($arr_attributes as $attribute_slug=> $variation_slug) {
$term = get_term_by('slug', $variation_slug, $attribute_slug);
if (isset($term)) {
if (strlen($str_name) > 0) $str_name.= ', ';
$str_name.= $term -> name;
}
}
}
return $str_name;
}