Woocommerce: get product variation title

2019-05-15 08:52发布

I'm writing a plugin and cannot get the correct variation title In Woocommerce the variation i use is called "unfolded laminated". but when i try to get the title of a variation i get: "Variation #781 of Chart"

This is the code is use:

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']);
    } 
}

How do i get the correct title?

3条回答
ゆ 、 Hurt°
2楼-- · 2019-05-15 09:40

I was actually looking this up trying to figure it out and here's my solution because the variation title was returning a slug.

Tested on 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'];
查看更多
聊天终结者
3楼-- · 2019-05-15 09:41

Here is a solution for this problem which is tested with 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']);
    }
  }
}
查看更多
小情绪 Triste *
4楼-- · 2019-05-15 09:48

I stumbled across this just now looking for a 'quick' fix. Since no-one has posted an answer I thought I would.

I just used WordPress get_post_meta to fetch attribute_options. This is where all the option titles are stored (variation titles are product options).

$product_options = get_post_meta($item['variation_id'], 'attribute_options');

Will return an array

    [attribute_options] => Array
    (
        [0] => Some Variation Title
    )
查看更多
登录 后发表回答