我正在运行一个功能,通过该功能,我检查用户是否在之前的订单中有退款商品,如果有,则在结账时将信用额度作为负购物车费用。该功能适用于之前下过订单但在新用户的网站上导致严重错误的用户。
Fatal error: Uncaught Error: Call to a member function get_refunds() on bool in /wp-content/themes/my-theme/refunds.php:20 Stack trace:
#0 /wp-includes/class-wp-hook.php(287): add_last_order_refund_total_at_checkout(Object(WC_Cart))
#1 /wp-includes/class-wp-hook.php(311): WP_Hook->apply_filters('', Array)
#2 /wp-includes/plugin.php(478): WP_Hook->do_action(Array)
#3 /wp-content/plugins/woocommerce/includes/class-wc-cart.php(1714): do_action('woocommerce_car...', Object(WC_Cart))
#4 /wp-content/plugins/woocommerce/includes/class-wc-cart-totals.php(270): WC_Cart->calculate_fees()
#5 /wp-content/plugins/woocommerce/includes/class-wc-cart-totals.php(829): WC_Cart_Totals->get_fees_from_cart()
#6 /wp-content/plugins/woocommerce/includes/class-wc- in /wp-content/themes/my-theme/refunds.php on line 20
这是检查上一个订单是否有任何退款的代码:
//Check total of refunded items from last order - add as a fee at checkout
function add_last_order_refund_total_at_checkout($cart_object){
if ( is_admin() && ! defined( 'DOING_AJAX' ) )
return;
$user_id = get_current_user_id(); // The current user ID
$customer = new WC_Customer( $user_id );
$last_order = $customer->get_last_order();
$order_id = $last_order;
// Get the WC_Order Object instance (from the order ID)
$order = wc_get_order( $order_id );
// Get the Order refunds (array of refunds)
$order_refunds = $order->get_refunds();
$total_to_refund = $order->get_total_refunded()*(-1);//WIP need to check which items have tax
if (!empty($order_refunds)) WC()->cart->add_fee( 'Refund', $total_to_refund );
}
add_action( 'woocommerce_cart_calculate_fees', 'add_last_order_refund_total_at_checkout', 10, 1 );
我相信我需要首先检查用户是否有任何先前的订单,否则 get_refund() 会导致错误,因为他们没有任何要检查的订单?我将如何安全地做到这一点?