我试图创建一个单一的产品页面的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);
我试过使用add_filter,但不起作用。
1条答案
按热度按时间q1qsirdb1#
我重新看了你的代码,因为有一些错误,错误和遗漏的东西。这里,缺少的是产品添加到购物车表单中的隐藏输入字段,用于在添加到购物车操作中发布您的自定义价格。然后,您将能够使用该自定义价格。
由于您似乎正在插件中使用您的代码,您应该开始将以下内容添加到主插件文件中,以检查WooCommerce是否处于活动状态:
将CSS样式文件排入队列需要单独的函数 (您可能需要在样式规则中进行一些CSS更改):
对于您的自定义数据库查询,最好在单独的函数 * 中设置每个查询(原因:代码模块化)*:
下面是您重新访问的代码函数,挂接在另一个钩子中(我在产品表单中包含了一个强制性的隐藏输入字段):
现在,要将更新后的价格作为自定义购物车项目数据包含在内,我们使用以下命令:
因此,我们现在可以在Minicart中显示具有此自定义更新价格的项目:
最后,我们使用自定义更新价格设置购物车项目价格:
代码放在你的活动子主题(或活动主题)的functions.php文件中,或者也放在插件中。测试和作品。
相关:自定义购物车项目价格设置从产品隐藏的输入字段在Woocommerce 3