gpt4 book ai didi

php - 更改 WooCommerce 购物车项目名称

转载 作者:可可西里 更新时间:2023-11-01 00:08:13 25 4
gpt4 key购买 nike

目标是在项目传递到我们的支付网关时更改项目名称,但保留原样以显示在我们的产品页面上。

我已经在我的 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 过滤器 Hook 是一个前端 Hook ,位于:

1) WooCommerce 模板:

  • emails/plain/email-order-items.php
  • templates/order/order-details-item.php
  • templates/checkout/form-pay.php
  • templates/emails/email-order-items.php

2)WooCommerce 核心文件:

  • 包含/class-wc-structured-data.php

Each of them has $item_name common first argument, and different for the other arguments.
See Here for more details…

您在函数中设置了 2 个参数(第二个参数并非对所有模板都是正确的)并且您在钩子(Hook)中只声明了一个。我已经测试了下面的代码:

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;
}

它适用于

  • 订单接收(谢谢)页面,
  • 电子邮件通知
  • 和我的账户订单 > 单笔订单详情

但不在购物车、结帐和后端订单编辑页面中。

So if you need to make it work on Cart and Checkout, you should use other hooks like woocommerce_before_calculate_totals.
Then you can use WC_Product methods (setter and getters).

这是你的新代码

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 文件。

现在除了 Shop archives 和产品页面之外,你已经更改了所有地方的名称......

此代码已经过测试并适用于 WooCommerce 2.5+ 和 3+

If you want to keep original item names in cart only you should add this conditional WooCommerce tag inside the function:

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

此答案已于 2017 年 8 月 1 日更新,以获得 woocommerce 先前版本的兼容性......

关于php - 更改 WooCommerce 购物车项目名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44994359/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com