问题
I'm trying to change the name of the product in cart and checkout pages.
I have the following code to add some cart meta data:
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 );
But I also want to change the name of the product.
For example if the product name is Apple
and custom field 'sample_value'
value is with sugar
, I would like to get Apples (with sugar)
.
How can I achieve this?
回答1:
Using a custom function hooked in woocommerce_before_calculate_totals
action hook:
// Changing the cart item name
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;
}
}
}
The Code goes in function.php file of your active child theme (or theme) or also in any plugin file.
This code is tested and works.
来源:https://stackoverflow.com/questions/45415887/append-custom-field-value-in-woocommerce-product-name-on-cart-and-checkout