【问题标题】:WooCommerce - Adding a custom price to each product in cartWooCommerce - 为购物车中的每个产品添加自定义价格
【发布时间】:2016-08-31 18:12:54
【问题描述】:

我想使用这段简单的代码update_post_meta( $product->id, '_regular_price', $frame_price_added); 在购物车中添加自定义价格来更新产品价格。

注意:我想要实现的是将此自定义价格添加到购物车中的每个产品。

我尝试通过这种方式获取$frame_price_added

$frame_price = $res['_number_field'][0];
$frame_price_added = $product->price + $frame_price;

这里$product->price 是来自woocomerce 产品的价格,$frame_price 是来自我新添加的价格。

我想知道如何将这个新价格关联到购物车,因为它不起作用。

我尝试过使用update_post_meta( $product->id, '_price', $frame_price_added);,当页面刷新时,它会将自定义价格添加并存储到产品中,然后保存。

关于如何正确实现这一点的任何想法?

谢谢。


编辑:还有一件事……我搜索了一个可以在添加到购物车时调用的函数,但我没有找到任何东西,还有一个在 woocommerce_template_single_add_to_cart 上调用的动作挂钩有woocommerce_single_product_summary,但没有找到任何功能。

【问题讨论】:

  • WooCommerce 将_regular_pricesale_price 和销售价格的销售日期进行比较以确定_price 键。 _price 是用户将支付的价格。我能说的最好的,听起来你可能想考虑Product Addons
  • @helgatheviking 哦,我一直在阅读所有关于 wordpress 表单的 cmets -_- 我也读到了同样的内容:p 抱歉再次问这个问题,但我正在寻找一种方法,如果我们更新实际价格正确地送达购物车。所以我在想的是添加一个钩子并在结帐后更新该钩子中的这些价格销毁它们

标签: php wordpress woocommerce cart product


【解决方案1】:

更新:对于 WooCommerce 3.0+ Change cart item prices in WooCommerce version 3.0

您可以使用 woocommerce_before_calculate_totals 挂钩来自定义您的购物车商品价格。

您可以通过这种方式在您的函数中将 $framed_price 变量定义为全局变量。

这是代码:

// getting your additional price outside the function (making any conditional calculations) 
$framed_price = 20;

add_action( 'woocommerce_before_calculate_totals', 'add_custom_total_price', 10 );
function add_custom_total_price( $cart_object ) {

    if ( is_admin() && ! defined( 'DOING_AJAX' ) )
        return;

    global $framed_price;

    foreach ( $cart_object->get_cart() as $key => $value ) {
        $value['data']->price += $framed_price;
    }
}

或者在挂钩函数中获取您的自定义价格(可选,取决于您获取自定义价格的方式)

add_action( 'woocommerce_before_calculate_totals', 'add_custom_total_price', 10 );
function add_custom_total_price( $cart_object ) {

    if ( is_admin() && ! defined( 'DOING_AJAX' ) )
        return;

    $framed_price = 20;

    foreach ( $cart_object->get_cart() as $key => $value ) {
        $value['data']->price += $framed_price;
    }
}

此代码已经过测试并且可以运行。

这个代码自然会出现在您的活动子主题(或主题)的 function.php 文件中或任何插件文件中。

参考:WooCommerce Cart - Dynamic Price variable pass into custom price hook

【讨论】:

  • 如何从我的表单中获取 $framed_price ?我不希望它是静态的
  • @sona 你到底是什么意思/想要什么?什么形式,什么领域?
猜你喜欢
  • 2018-10-31
  • 2017-01-08
  • 2019-12-21
  • 2015-11-28
  • 1970-01-01
  • 2015-05-27
  • 2015-12-04
  • 2020-09-01
  • 1970-01-01
相关资源
最近更新 更多