[英]Woocommerce: get product variation title
我正在编写一个插件,但无法获得正确的变体标题在 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']);
}
}
我如何获得正确的标题?
我实际上正在查找这个试图弄清楚,这是我的解决方案,因为变体标题返回了一个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'];
我刚刚偶然发现了这个问题,正在寻找“快速”解决方案。 由于没有人发布答案,我以为我会。
我只是使用 WordPress get_post_meta
来获取attribute_options
。 这是存储所有选项标题的地方(变体标题是产品选项)。
$product_options = get_post_meta($item['variation_id'], 'attribute_options');
将返回一个数组
[attribute_options] => Array
(
[0] => Some Variation Title
)
这是此问题的解决方案,已使用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']);
}
}
}
在此函数中,返回输入变体的标题,您可以将分隔符 ', ' 更改为空格或任何需要的内容。
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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.