WooCommerce Hook woocommerce_cancelled_order

时间:2017-12-13 23:16:33

标签: php wordpress woocommerce hook-woocommerce

美好的一天,

这是我第一次使用stackoverflow,很高兴见到你们。

Anywho,我正在为WooCommerce写一个插件,我会在取消订单时自动退款。当我在没有钩子的单独文件中手动执行它时,我的代码工作正常,但是,我的钩子似乎没有执行。我正在做以下事情:

{{1}}

我添加了第一个重定向行,仅用于测试是否重定向,但它没有!知道为什么这个钩子不会被解雇吗?

2 个答案:

答案 0 :(得分:1)

使用适当的操作woocommerce_order_status_cancelled

这里是例子

add_action( 'woocommerce_order_status_cancelled', 'change_status_to_refund', 10, 1 );

public function change_status_to_refund( $order_id ){
    //Do Something here
}

答案 1 :(得分:0)

感谢您的评论。似乎woocommerce_order_status_cancelled挂钩很好,但参数是$ order_id。经过大量的调试后,我有以下几点:

add_action( 'woocommerce_order_status_cancelled', 'change_status_to_refund', 
21, 1 );
function change_status_to_refund( $order_id ) {

$order = new WC_Order( $order_id );      

$noRefundLimit = 24 * 60; //in minutes until booking

global $wpdb;
$querystr = "
SELECT $wpdb->posts.* 
FROM $wpdb->posts 
WHERE $wpdb->posts.post_parent = $order_id
";

$pageposts = $wpdb->get_results($querystr, OBJECT);

 $bookingId = current($pageposts)->ID;

 $bookingStart = current(get_post_meta($bookingId, "_booking_start"));
 $time = (new DateTime($bookingStart, new 
 DateTimeZone("America/Los_Angeles")))->getTimestamp();
 $nowTime = (new DateTime())->getTimestamp();
 $difference = round(($time - $nowTime)/60);//in minutes

 if($difference >= $noRefundLimit) {
     $refundPercentage = 1; //how much will we give back? fraction of 1.
     // Get Items
     $order_items   = $order->get_items();

     // Refund Amount
       $refund_amount = 0;
     // Prepare line items which we are refunding
     $line_items = array();

     if ( $order_items ) {
       foreach( $order_items as $item_id => $item ) {
        $refund_amount += $item->get_total();
       }
     }
     $refund_amount = ($refund_amount * $refundPercentage);
     $refund_reason = "Order Cancelled";
     $refund = wc_create_refund( array(
       'amount'         => $refund_amount,
       'reason'         => $refund_reason,
       'order_id'       => $order_id,
       'line_items'     => $line_items,
       'refund_payment' => true
       ));

       $order->update_status('wc-refunded', 'Order Cancelled And Completely 
        Refunded');
     }
}

我遇到了一些问题。即使订单已付款,$ order-> is_paid()也会返回false(我认为这是因为状态从付费更改为已取消/退款)所以我的代码甚至没有达到目的。然后get_posts没有按预期工作。我被迫使用$ wpdb。之后我的代码工作了。