2017-07-31 3 views
2

カートとチェックアウトページで商品の名前を変更しようとしています。WooCommerceの商品名にカスタムフィールドの値を追加してカートとチェックアウトに追加

は、私はいくつかのカートのメタデータを追加するには、次のコードを持っている:

function render_meta_on_cart_and_checkout($cart_data, $cart_item = null) { 
    $custom_items = array(); 
    /* Woo 2.4.2 updates */ 
    if(!empty($cart_data)) { 
     $custom_items = $cart_data; 
    } 

    if(isset($cart_item['sample_name'])) { 
     $custom_items[] = array("name" => $cart_item['sample_name'], "value" => $cart_item['sample_value']); 
    } 
    return $custom_items; 
} 
add_filter('woocommerce_get_item_data', 'render_meta_on_cart_and_checkout', 10, 2); 

をしかし、私はまた、製品の名前を変更したいです。例えば

製品名は、値がwith sugarあるAppleとカスタムフィールド'sample_value'であれば、私はApples (with sugar)を取得したいと思います。

どうすればこの問題を解決できますか?

答えて

0

あなたはwoocommerce_before_calculate_totalsアクションフックにこの方法を夢中にカスタム関数を使用する必要があります。

// Changing the cart item price based on custom field calculation 
add_action('woocommerce_before_calculate_totals', 'customizing_cart_items_name', 10, 1); 
function customizing_cart_items_name($cart_object) { 

    if (is_admin() && ! defined('DOING_AJAX')) 
     return; 

    // Iterating through each cart items 
    foreach ($cart_object->get_cart() as $cart_item) { 
     // Continue if we get the custom 'sample_name' for the current cart item 
     if(empty($cart_item['sample_name'])){ 
      // An instance of the WC_Product object 
      $wc_product = $cart_item['data']; 
      // Get the product name (WooCommerce versions 2.5.x to 3+) 
      $product_name = method_exists($wc_product, 'get_name') ? $wc_product->get_name() : $wc_product->post->post_title; 
      // The new string composite name 
      $product_name .= ' (' . $cart_item['sample_name'] . ')'; 

      // Set the new composite name (WooCommerce versions 2.5.x to 3+) 
      if(method_exists($wc_product, 'set_name')) 
       $wc_product->set_name($product_name); 
      else 
       $wc_product->post->post_title = $product_name; 
     } 
    } 
} 

コードは、あなたのアクティブな子テーマ(またはテーマ)のfunction.phpファイルやも任意のプラグインファイルになります。

このコードは、wooCommerceバージョン2.5.xから3.1+で動作確認されています。

関連する問題