我正在try 创建一个单一产品页面的WooCommerce插件.我需要添加常规定价与定制定价.我能够得到常规价格和定制价格的总和,但当我点击"添加到购物车"时,我无法在购物车中设置新的计算价格.
如有任何帮助,我们不胜感激.
// WooCommerce activation
function custom_product_page()
{
global $wpdb;
global $product;
wp_enqueue_style('my-plugin-styles', plugins_url('assets/css/diamond_style.css', __FILE__));
if (class_exists('WooCommerce') && is_product()) {
$product = wc_get_product(get_the_ID());
$product_categories = wp_get_post_terms(get_the_ID(), 'product_cat');
$is_ring = false;
foreach ($product_categories as $product_category) {
if ($product_category->slug === 'rings' || $product_category->slug === 'ring') {
$is_ring = true;
break;
}
}
$table_name = $wpdb->prefix . 'diamond_purity';
$ring_size_table = $wpdb->prefix . 'ring_size';
// Show Metal Color only if the product category is "ring"
if ($is_ring) {
// Retrieve the latest gold rate
$gold_rate_table = $wpdb->prefix . 'gold_rate';
$gold_rate = $wpdb->get_var("SELECT final_price FROM $gold_rate_table ORDER BY id DESC LIMIT 1");
// Get the net weight attribute
$net_weight = $product->get_attribute('net-weight-g');
// Get the regular price
$regular_price = $product->get_regular_price();
// Calculate the updated price
$updated_price = ($gold_rate * $net_weight) + $regular_price;
// Display the updated price
echo '<p class="productprice">₹' . $updated_price . '</p>';
$gross_weight = $product->get_attribute('gross-weight');
echo 'Weight: ' . $gross_weight . ' g';
// Update cart item price with the custom price
add_filter('woocommerce_add_cart_item', function ($cart_item) use ($updated_price) {
$cart_item['data']->set_price($updated_price);
return $cart_item;
});
}
}
}
add_action('woocommerce_single_product_summary', 'custom_product_page', 25);
我try 使用ADD_FILTER,但不起作用.