2017-07-31 60 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); 

但我也想改變產品的名稱。

例如,如果產品名稱爲Apple和自定義字段'sample_value'with sugar,我想獲得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+。

相關問題