簡體   English   中英

Woocommerce:獲取產品變體標題

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM