如何在woocommerce中为购物车创建自定义折扣

时间:2014-04-08 05:37:05

标签: php wordpress woocommerce

我在WooCommerce中创建了一个插件,并且在向CART / CHECKOUT页面添加自定义折扣时遇到了一个小问题。

如何在不创建优惠券的情况下将自定义折扣应用于购物车? 假设我想在购物车页面上给予5美元的折扣。我怎样才能做到这一点?

以下是我使用优惠券申请折扣的插件文件中的代码,但我想在不使用优惠券的情况下添加其他自定义折扣。

动作挂钩插件文件:

add_action('woocommerce_calculate_totals',array(&$this,'cart_order_total_action'));

及其在插件文件中的功能是:

public function cart_order_total_action(){
    if ( is_user_logged_in() ){
        global $woocommerce;
        global $current_user;
        global $wpdb;
        $u_id = $current_user->ID;
        $table_name = $wpdb->prefix."woocommerce_customer_reward_ms";
        $thetable2  = $wpdb->prefix . "woocommerce_customer_reward_cart_ms";
        $table_name3 = $wpdb->prefix."woocommerce_customer_reward_points_log_ms";
        $data       = $wpdb->get_row("SELECT * from $table_name where id=$u_id");
        $data2      = $wpdb->get_row("SELECT * from $thetable2");
        /* Order Id goes here */
        $orders=array();//order ids
        $args = array(
            'numberposts'     => -1,
            'meta_key'        => '_customer_user',
            'meta_value'      => $current_user->ID,
            'post_type'       => 'shop_order',
            'post_status'     => 'publish',
            'tax_query'=>array(
                    array(
                        'taxonomy'  =>'shop_order_status',
                        'field'     => 'slug',
                        'terms'     =>'on-hold'
                        )
            )  
        );
        $posts=get_posts($args);
        $orders=wp_list_pluck( $posts, 'ID' );
        $order = $orders[0];
        /* Order Id ends here */
        if($data){
            $user_points = $data->points;
            $points_set  = $data2->woo_pts_set;
            $coupon_code = 'wooreward_discount';
            if($user_points>=$points_set){
                // this following Code is optional and can be removed......as there is no need of if statement here
                if ( $woocommerce->cart->has_discount( $coupon_code ) ) {
                    /*$woocommerce->add_error( __('Coupon Code Already Applied.!!','woocommerce'));*/
                    return false;
                }else{
                    $woocommerce->cart->add_discount(sanitize_text_field($coupon_code));
                    $woocommerce->add_message( __('Taxco925 Reward Discount Applied.!!','woocommerce'));
                }
            }else{
                $woocommerce->add_error( __('Not Enough Taxco925 Points.!!','woocommerce'));
            }
        }else{
            $woocommerce->add_error( __('You have have not earned any Taxco925 Points yet.!!','woocommerce'));
        }
    }
}

正如您所看到的那样$woocommerce->cart->add_discount(sanitize_text_field($coupon_code)); 将我的折扣添加到购物车。但它在后台使用优惠券来做到这一点。有没有办法可以在不使用优惠券的情况下添加自定义折扣。

4 个答案:

答案 0 :(得分:7)

add_action('woocommerce_checkout_order_processed','custom_disount',10,1);
function custom_disount($order_id){
    $order = wc_get_order($order_id);
    $order_items = $order->get_items();
    foreach ($order_items as $order_item_key => $order_item) {
        $product = new WC_Product((int) $order_item['product_id']);
        $quantity = (int) $order_item['qty'];
        $discount=($product->regular_price*30)/100;  //30% disount.
        wc_update_order_item_meta($order_item_key,'_line_total',($product->regular_price*$quantity)-($discount*$quantity));
    }
}

答案 1 :(得分:5)

您可以使用“woocommerce_get_discounted_price”挂钩为购物车中的每件商品添加折扣。 例如:

function filter_woocommerce_get_discounted_price( $price, $values, $instance ) { 
//$price represents the current product price without discount
//$values represents the product object
//$instance represent the cart object 
$discount = 300;    // add custom discount rule , This is just an example
return ($price - $discount); 
}; 
 add_filter('woocommerce_get_discounted_price','filter_woocommerce_get_discounted_price', 10, 3 ); 

答案 2 :(得分:4)

可能为时已晚,但如果有人有其他解决方案告诉我。

我用的是:

$discount = floatval(10);
if(!empty($discount) || $discount != 0){
    $discount *= -1; // convert positive to negative fees
    $woocommerce->cart->add_fee('discount', $discount, true, '' ); // add negative fees
}

如果您使用PayPal标准付款,则会收到错误,因为您无法提交具有负价格的产品。

您只需编辑paypal woocommerce插件即可传递此值。

但其他付款方式还可以!

最诚挚的问候,

答案 3 :(得分:1)

添加负值费用将不会产生正确的总费用。 费用金额上加了税,导致总费用高于预期。

在从购物车创建订单之前,您需要创建一个“优惠券”并将其应用到购物车(如果直接将其应用到$ order上,则计算不正确)。然后重新计算购物车->总计,最后从购物车中创建一个订单,保存订单后,您可以根据需要删除“动态”创建的“优惠券”。您可以创建具有任何动态$ value和任何类型(固定,百分比等)的动态优惠券。

这是在woo3 +中添加折扣的唯一方法。 在折扣方面,收费是错误的。还要说说费用“不要在这里使用负值!”。

我猜你想举个例子吗?

这里。...

<?php 

// this code inside wordpress and with woo3+ of course......
// you have to figure out the rest yourself, how to implement it. but here it is...

$order_data = array (
  'status' => 'on-hold' // or whatever order staus
  // can have more data if need here... 
);

// below creates a coupon with discount_type = fixed_cart, default.
$coupon = array (
  'post_title'    => 'coupon_discount',
  'post_status'   => 'publish',
  'post_type'     => 'shop_coupon'
);
// can be modified with update_post_meta discount_type = percent and so on....

$dynamic_discount = 20; // yes, just a number can be from another dynamic input source....

$new_coupon_id = wp_insert_post( $coupon ); // add the coupon to the cart
add_post_meta( $new_coupon_id , 'coupon_amount' , $dynamic_discount , true ); // add the "discount" value ($dynamic_discount)..... depends on discount_type... in this case fixed_cart

WC()->cart->add_to_cart( 2122 , 2 ); // add products, product_id , quantity ..... can be in a loop.
WC()->cart->add_discount( 'coupon_discount' ); // APPLY THE COUPON WITH DISCOUNT -> This is the trick....
WC()->cart->calculate_totals(); // do some math on the "cart"
WC()->checkout(); // yes, checkout the "cart", now with the discount....
$order_id = WC()->checkout()->create_order( $order_data ); // basic order data, see the top in this script.. get new created order_id.
$order = wc_get_order( $order_id ); // get the order...
// can do more with $order here if want, but NOT any coupons... it just not work in $order as is...
$order->calculate_totals(); // math
WC()->cart->empty_cart(); // empty cart....
$order->save(); // save the order...

wp_delete_post( $new_coupon_id , true ); // IF you  want to delete the "dynamic" coupon created above... up 2 u, if not you will end up with a lot of coupons

// sorry, a bad example, uggly code, but at least it work.... :)
// btw, i like Pattaya, send bitcoins :)

// Again, sorry for uggly code...
?>