prosource

woocommerce에서 카트에 대한 커스텀 할인을 생성하는 방법

probook 2023. 3. 29. 21:37
반응형

woocommerce에서 카트에 대한 커스텀 할인을 생성하는 방법

WooCommerce에서 플러그인을 만들고 있는데 CART / CHECKUP 페이지에 커스텀 할인을 추가하는 데 약간의 문제가 있습니다.

쿠폰을 작성하지 않고 카트에 커스텀 할인을 적용하는 방법은 무엇입니까?예를 들어 카트 페이지에서 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));카트에 할인이 추가됩니다.그러나 그것은 그렇게 하기 위해 배경에 쿠폰을 사용합니다.쿠폰을 사용하지 않고 커스텀 할인을 추가할 수 있는 방법이 있나요?

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));
    }
}

"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 ); 

너무 늦었을지도 모르지만, 누군가 다른 해결책이 있다면 말해 주세요.

다음과 같은 것을 사용합니다.

$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 standard payment를 사용할 경우 마이너스 가격으로는 상품을 제출할 수 없기 때문에 오류가 발생하였습니다.

이 값을 전달하려면 paypal woocommerce 플러그인을 편집하기만 하면 됩니다.

하지만 다른 결제방법은 OK!

안부 전합니다,

마이너스 가치의 추가 요금은 올바른 합계 요금이 되지 않습니다.수수료 금액에 세금이 추가되어 총 수수료가 예상보다 높아집니다.

카트에서 주문을 작성하기 전에 "쿠폰"을 작성하여 카트에 적용해야 합니다($주문에 직접 적용하면 올바르게 계산되지 않습니다).그런 다음 카트의 합계를 다시 계산하고 최종적으로 카트에서 주문을 작성합니다.주문을 저장한 후 필요에 따라 작성된 "동적" "쿠폰"을 삭제할 수 있습니다.동적 쿠폰은 동적 $값 및 유형(고정, 백분율 등)에 관계없이 작성할 수 있습니다.

이것이 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...
?>

언급URL : https://stackoverflow.com/questions/22928367/how-to-create-custom-discount-for-the-cart-in-woocommerce

반응형