WooCommerce在向管理员添加订单商品时更改价格

时间:2020-02-04 16:37:39

标签: wordpress woocommerce

我们有折扣率不同的客户。将产品添加到购物车时,所有这些都已编程并在前端工作,但是如果使用后端订单管理员添加新产品,我似乎无法找到一种基于用户折扣来计算新产品价格的方法。将产品添加到订单管理员中的现有订单中时,是否可以更改woocommerce_new_order_item挂钩中的价格?

这是我到目前为止所拥有的:

function action_woocommerce_new_order_item( $item_id, $item, $order_id ) { 
    // only run this from the WP admin section
    if ( !is_admin() )
        return;

    $item_type = $item->get_type();

    // return if this is not a product (i.e. fee, tax, etc.)
    if ( $item_type != 'line_item' )
        return;

    $product = wc_get_product( $item->get_product_id() );

    if ( !$product )
        return;

    $current_price = $product->get_price();
    $quantity = $item->get_quantity();

    // here I get the order's user's discount percentage and calculate the new discounted price
    // custom function
    $discounted_price = get_discounted_price( $current_price, $users_discount );

    $new_price = ( !empty($discounted_price) ) ? $discounted_price : $current_price;

    // this doesn't work
    $item->set_price( $new_price );

    // and this doesn't work
    $product->set_price( $new_price );

    // this appears to work but I'm not sure if this the best way to accomplish this
    $item->set_total( $price * $quantity );
}
add_action( 'woocommerce_new_order_item', 'action_woocommerce_new_order_item', 10, 3 );

任何帮助将不胜感激! 谢谢

1 个答案:

答案 0 :(得分:0)

这可用于在订单管理屏幕中添加商品元并更改商品价格:

function action_woocommerce_new_order_item( $item_id, $item, $order_id ) { 
    // only run this from the WP admin section
    if ( !is_admin() )
        return;

    $item_type = $item->get_type();

    // return if this is not a product (i.e. fee, tax, etc.)
    if ( $item_type != 'line_item' )
            return;

    $product = wc_get_product( $item->get_product_id() );

    if ( !$product )
            return;

    $current_price = $product->get_price();
    $size = $product->get_attribute('size');

    // add custom item meta to order
    if ( $size ) {
            wc_add_order_item_meta( $item_id, 'Size', $size , false );
    }

    $order = wc_get_order( $order_id );

    $order_user = $order->get_user();
    $order_user_id = $order->get_user_id();

    // get this order's user's discount %
    $users_discount = get_user_meta( $order_user_id, 'discount', true );
    $users_discount = ( $users_discount > 0 ) ? $users_discount : 0;

    // calculate the discounted price based on the user's discount (custom function)
    $discounted_price = get_discounted_price( $current_price, $users_discount );

    $quantity = $item->get_quantity();
    $new_price = ( !empty($discounted_price) ) ? $discounted_price : $current_price;

    $item->set_total( $new_price * $quantity );
}; 
add_action( 'woocommerce_new_order_item', 'action_woocommerce_new_order_item', 10, 3 );