将WooCommerce产品名称中的自定义字段值附加到购物车并结帐
问题描述:
我试图更改购物车和结帐页面中产品的名称。将WooCommerce产品名称中的自定义字段值附加到购物车并结帐
我有下面的代码添加一些车元数据:
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)
。
我该如何做到这一点?
答
你应该使用woocommerce_before_calculate_totals
动作钩子钩住这样的自定义函数:
// Changing the cart item price based on custom field calculation
add_action('woocommerce_before_calculate_totals', 'customizing_cart_items_name', 10, 1);
function customizing_cart_items_name($cart_object) {
if (is_admin() && ! defined('DOING_AJAX'))
return;
// Iterating through each cart items
foreach ($cart_object->get_cart() as $cart_item) {
// Continue if we get the custom 'sample_name' for the current cart item
if(empty($cart_item['sample_name'])){
// An instance of the WC_Product object
$wc_product = $cart_item['data'];
// Get the product name (WooCommerce versions 2.5.x to 3+)
$product_name = method_exists($wc_product, 'get_name') ? $wc_product->get_name() : $wc_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($wc_product, 'set_name'))
$wc_product->set_name($product_name);
else
$wc_product->post->post_title = $product_name;
}
}
}
的代码放在你的活跃儿童主题(或主题)的function.php文件或也以任何插件文件。
此代码已经过测试,适用于wooCommerce版本2.5.x至3.1+。