我使用以下代码来更改结账页面上的产品名称,但我只需要为一种产品执行此操作。我无法弄清楚如何定位特定的产品 ID:
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;
}
}
代码将 WooCommerce 结账页面上的所有产品名称更改为新产品名称。但我只需要对特定产品执行此操作(ID 为 134443 的产品)。
您的代码可以简化,针对特定产品更改其名称。尝试:
add_action( 'woocommerce_before_calculate_totals', 'change_specific_cart_item_name' );
function change_specific_cart_item_name( $cart ) {
if ( is_admin() && ! defined( 'DOING_AJAX' ) )
return;
$targeted_id = 134443; // HERE set the targeted product ID
$new_name = "The new product name"; // HERE set the desired new product name
// Loop through cart items
foreach ( $cart->get_cart() as $cart_item ) {
if ( $cart_item['product_id'] == $targeted_id ) {
$cart_item['data']->set_name($new_name);
}
}
}
代码位于子主题的functions.php 文件中(或插件中)。应该可以。