2 回答

TA貢獻1829條經驗 獲得超13個贊
如果您查看WC_Customer
?get_last_order()
方法文檔?或源代碼,您將看到:
/*
?* @return WC_Order|false
?*/
這意味著該get_last_order() 方法可以返回:
物體WC_Order_
或false布爾值。
所以你可以在你的代碼中使用:
$last_order = $customer->get_last_order();
if ( ! $last_order )? {
? ?return; // Exit (Not an order)
}
為了避免這個錯誤。
現在,您可以使用is_a()
php 條件函數來檢查變量是否來自特定的 Object 類,而不是其他變量,例如:
$last_order = $customer->get_last_order();
if ( ! is_a( $last_order, 'WC_Order' ) ) {
? ?return; // Exit (Not an order)
}
// Your other code…?
或者您可以使用?method_exists()
php 條件函數作為WC_Order
?get_refunds()
方法,以檢查 a 變量是否來自特定的 Object 類而不是其他內容:
$last_order = $customer->get_last_order();
if ( ! method_exists( $last_order, 'get_refunds' ) )? {
? ?return; // Exit (Not an order)
}
// Your other code…
這三種情況工作得很好,避免了錯誤

TA貢獻1898條經驗 獲得超8個贊
這樣試試吧,已經添加了多個控件,見評論
// Check total of refunded items from last order - add as a fee at checkout
function add_last_order_refund_total_at_checkout( $cart ) {
if ( is_admin() && ! defined( 'DOING_AJAX' ) )
return;
// The current user ID
$user_id = get_current_user_id();
// User id exists
if ( $user_id > 0 ) {
$customer = new WC_Customer( $user_id );
// Get last order
$last_order = $customer->get_last_order();
// True
if ( $last_order ) {
// Get the order id
$order_id = $last_order->get_id();
// Order ID exists
if ( is_numeric( $order_id ) ) {
// 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();
// NOT empty
if ( ! empty( $order_refunds) ) {
// WIP need to check which items have tax
$total_to_refund = $order->get_total_refunded();
// Add fee
$cart->add_fee( 'Refund', $total_to_refund );
}
}
}
}
}
add_action( 'woocommerce_cart_calculate_fees', 'add_last_order_refund_total_at_checkout', 10, 1 );
- 2 回答
- 0 關注
- 143 瀏覽
添加回答
舉報