我试图在购物车和结帐页面中更改产品名称。
我有以下代码来添加一些购物车元数据:
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 :(得分: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', 20, 1 );
function customizing_cart_items_name( $cart ) {
if ( is_admin() && ! defined( 'DOING_AJAX' ) )
return;
if ( did_action( 'woocommerce_before_calculate_totals' ) >= 2 )
return;
// Loop through each cart items
foreach ( $cart->get_cart() as $cart_item ) {
// Continue if we get the custom 'sample_name' for the current cart item
if( empty( $cart_item['sample_name'] ) ){
// Get an instance of the WC_Product Object
$product = $cart_item['data'];
// Get the product name (Added compatibility with Woocommerce 3+)
$product_name = method_exists( $product, 'get_name' ) ? $product->get_name() : $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( $product, 'set_name' ) )
$product->set_name( $product_name );
else
$product->post->post_title = $product_name;
}
}
}
代码进入活动子主题(或主题)的function.php文件或任何插件文件中。
此代码经过测试并有效。