簡體   English   中英

更改WooCommerce購物車商品名稱

[英]Changing WooCommerce cart item names

目的是在商品名稱傳遞到我們的付款網關時更改其名稱,但將其保留原樣以在我們的產品頁面上顯示。

我已經在我的functions.php中嘗試過此操作:

function change_item_name( $item_name, $item ) {
    $item_name = 'mydesiredproductname';
    return $item_name;
}
add_filter( 'woocommerce_order_item_name', 'change_item_name', 10, 1 );

但這似乎對我沒有用。 我覺得我應該傳遞一個實際的商品ID或其他東西……我有點迷失了。

我在這里做錯了什么的任何信息,將不勝感激。

woocommerce_order_item_name過濾器掛鈎是一個前端掛鈎,位於:

1)WooCommerce模板:

  • emails / plain / email-order-items.php
  • template / order / order-details-item.php
  • 模板/結帳/form-pay.php
  • 模板/電子郵件/電子郵件訂單-items.php

2)WooCommerce Core文件:

  • includes / class-wc-structured-data.php

每個參數都有$ item_name公用的第一個參數,其他參數不同。
有關更多詳細信息,請參見此處

您在函數中設置了2個參數(第二個參數不適用於所有模板),並且您僅在鈎子中聲明了一個。 我已經測試了以下代碼:

add_filter( 'woocommerce_order_item_name', 'change_orders_items_names', 10, 1 );
function change_orders_items_names( $item_name ) {
    $item_name = 'mydesiredproductname';
    return $item_name;
}

它適用於

  • 訂單接收(謝謝)頁面,
  • 電子郵件通知
  • 和“我的帳戶訂單”>“單個訂單詳細信息”

但不在購物車,結帳和后端訂單編輯頁面中。

因此,如果需要在Cart和Checkout上使用它,則應使用woocommerce_before_calculate_totals類的其他鈎子。
然后,您可以使用WC_Product methods (setter和getter)。

這是您的新代碼

add_action( 'woocommerce_before_calculate_totals', 'custom_cart_items_prices', 10, 1 );
function custom_cart_items_prices( $cart ) {

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

    if ( did_action( 'woocommerce_before_calculate_totals' ) >= 2 )
        return;

    // Loop through cart items
    foreach ( $cart->get_cart() as $cart_item ) {

        // Get an instance of the WC_Product object
        $product = $cart_item['data'];

        // Get the product name (Added Woocommerce 3+ compatibility)
        $original_name = method_exists( $product, 'get_name' ) ? $product->get_name() : $product->post->post_title;

        // SET THE NEW NAME
        $new_name = 'mydesiredproductname';

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

代碼會出現在您活動的子主題(或主題)的任何php文件中,也可能出現在任何插件的php文件中。

現在,您可以在除商店檔案和產品頁面之外的任何地方更改名稱。

此代碼已經過測試,可在WooCommerce 2.5+和3+上運行

如果只想在購物車中保留原始商品名稱,則應在函數內添加以下條件WooCommerce標簽

 if( ! is_cart() ){ // The code } 

該答案已於2017年8月1日更新,以獲取woocommerce兼容的先前版本…

我認為上層不錯的解決方案不再適用於woocommerce 3.7.1。 由於沒有升級,所以它一直在工作。 可能更新?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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