Php Woocommerce:获得产品变体标题
我正在编写插件,无法获得正确的变体标题 在Woodcommerce中,我使用的变体称为“展开层压”。但当我试图得到一个变体的标题时,我得到了:“变体#781图表” 这是使用的代码:Php Woocommerce:获得产品变体标题,php,wordpress,woocommerce,Php,Wordpress,Woocommerce,我正在编写插件,无法获得正确的变体标题 在Woodcommerce中,我使用的变体称为“展开层压”。但当我试图得到一个变体的标题时,我得到了:“变体#781图表” 这是使用的代码: foreach ($order->get_items() as $item) { $product_variation_id = $item['variation_id']; if ($product_variation_id) { $product = new WC_P
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']);
}
}
如何获得正确的标题?我刚才偶然发现了这个问题,正在寻找“快速”解决方案。因为没有人给出答案,我想我会的 我刚刚使用WordPress
get\u post\u meta
获取属性选项。这是存储所有选项标题的地方(变体标题是产品选项)
将返回一个数组
[attribute_options] => Array
(
[0] => Some Variation Title
)
我实际上是在查找这个,试图找出答案,这是我的解决方案,因为变体标题返回了一个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'];
以下是此问题的解决方案,已通过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;
}
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;
}