Dre*_*ell 3 php wordpress checkout cart woocommerce
目标是在商品名称传递到我们的付款网关时更改其名称,但将其保持原样显示在我们的产品页面上。
我已经在我的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 );
Run Code Online (Sandbox Code Playgroud)
但这似乎对我没有用。我觉得我应该传递一个实际的商品ID或其他东西……我有点迷失了。
我在这里做错了什么的任何信息,将不胜感激。
该woocommerce_order_item_name过滤器是钩前端钩和位于:
1)WooCommerce模板:
2)WooCommerce Core文件:
每个参数都有$ 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;
}
Run Code Online (Sandbox Code Playgroud)
它适用于
但不在购物车,结帐和后端订单编辑页面中。
因此,如果您需要使其在购物车和结帐平台上正常工作,则应使用其他挂钩
woocommerce_before_calculate_totals。
然后,您可以使用WC_Product methods(设置程序和获取程序)。
这是您的新代码
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;
}
}
Run Code Online (Sandbox Code Playgroud)
代码会出现在您活动的子主题(或主题)的任何php文件中,也可能出现在任何插件的php文件中。
现在,您可以在除商店档案和产品页面之外的任何地方更改名称。
此代码已经过测试,可在WooCommerce 2.5+和3+上运行
如果只想在购物车中保留原始商品名称,则应在函数内添加以下条件WooCommerce标签:
Run Code Online (Sandbox Code Playgroud)if( ! is_cart() ){ // The code }
该答案已于2017年8月1日更新,以获取woocommerce兼容的先前版本…
| 归档时间: |
|
| 查看次数: |
5921 次 |
| 最近记录: |