Woocommerce: Get Product Name
I'm writing a plugin and can't get the variation name correct In Woocommerce, the variation I use is called "expanded laminated". but when I try to get the name of the variation, I get: "Change # 781 of the chart"
This code is used:
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?
source to share
I was actually looking for this while trying to figure it out and here is my solution because the variation name was returning a bullet.
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'];
source to share
I stumbled upon this now while looking for a "quick" fix. Since no one posted an answer, I thought I would.
I just used WordPress get_post_meta
to fetch attribute_options
. All option names are stored here (option names are product parameters).
$product_options = get_post_meta($item['variation_id'], 'attribute_options');
Will return an array
[attribute_options] => Array
(
[0] => Some Variation Title
)
source to share
Here is a solution to this problem that has been 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']);
}
}
}
source to share