Woocommerce,由管理员通过wp-admin添加时更新价格 [英] Woocommerce, update price when added by admin via wp-admin

查看:85
本文介绍了Woocommerce,由管理员通过wp-admin添加时更新价格的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当管理员仅通过管理员区域将产品添加到现有订单中时,我想设置50%的折扣.

I would like to set a 50% discount when and only when the admin adds a product to the existing order via the admin area.

我已经尝试过了:

function admin_set_custom_price( $item, $item_id ) {
    $item->set_subtotal( ( ( ( 100 - 50 ) * $item->get_subtotal() ) / 100 ) );
    $item->set_total( ( ( ( 100 - 50 ) * $item->get_total() ) / 100 ) );

    $item->apply_changes();
    $item->save();

    return $item;
}
add_filter( 'woocommerce_ajax_order_item', 'admin_set_custom_price', 10, 2 );

结果是,添加商品时,价格为原始价格.

And the result is that when the item is added the price is the original price.

如果我随后仅刷新页面,它会以50%的折扣显示价格.

If I then simply refresh the page, it shows the prices with 50% discount.

添加价格后,我还需要怎么做才能立即显示折扣价格?

What else do I need to do show the price with discount right away when it is added without the need to refresh the page?

由于价格在刷新时是正确的,因此我猜想好像是某种东西在覆盖它,因为它保存了.

Looks like something is overriding it as it is saved I would guess since the price is correct on refresh.

谈论简单/变体产品类型.

Talking about simple/variation product types.

推荐答案

所以我改用了这个钩子:

So I've used this hook instead:

woocommerce_ajax_added_order_items

然后在函数中:

foreach ( $order->get_items() as $order_item_id => $order_item_data ) {
    //    Set custom price.
}

似乎可以正常工作.

事实证明,如果您想一次添加多个项目,上述挂钩只会获取最后一个项目.

It turns out that the above hook only get the last item in case you want to add multiple items at once.

仅在循环中对通过ajax添加的项目(不影响现有项目)执行的更好的钩子是:

A better hook which is executed in the loop ONLY for the items added via ajax (not affecting the existing ones) is:

woocommerce_ajax_add_order_item_meta

woocommerce_ajax_add_order_item_meta

然后在循环中,您可以对购物车中的商品进行循环,如果购物车ID匹配,则可以更改产品.

Then in the loop you can do a loop over the items in the cart and if the cart id matches, you can change the product.

function update_order_prices_on_admin_ajax( $item_id, $item, $order )
    foreach ( $order->get_items() as $order_item_id => $order_item_data ) {
        if ( $order_item_id == $item_id ) {
            // Do changes here.

            // Runs this after making a change to $order_item_data
            $order->apply_changes();
            $order->save();
        }
    }
}
add_action( 'woocommerce_ajax_add_order_item_meta', 'update_order_prices_on_admin_ajax', 99, 3 );

这篇关于Woocommerce,由管理员通过wp-admin添加时更新价格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆