i'm having a odd issue with WooCommerce.
I have a plugin I developed that sends data from WooCommerce orders to HubSpot. The plugin needs to fire whenever a new order is placed OR an existing order is updated . I've been using the following truncated code to try to achieve this:
add_action('save_post', 'printout', 10, 3);
function printout($post_ID, $post, $update)
{
if ("shop_order" == $post->post_type) {
$msg = $post_ID;
delegator($msg);
}
}
function delegator($order_id){
$order = get_woocommerce_order($order_id);
// assigns the actual data of the order to the $data variable
$data = get_woocommerce_order_data($order);
// assign User e-mail for search
$email = $order->get_billing_email();
//$email = get_post_meta( $order_id, '_billing_email', true );
}
The problem i'm having is that upon new Orders being made, WordPress can't get the order details, specifically a e-mail (it returns null). The hook does return an order number, so I don't think it's the hook doing this but something else.
The odd part is if after the order is placed and I go into the Order page and just hit update on the order, it works!
So I'm wondering what I'm missing / what's wrong here. Does the flow of the hook fire before WooCommerce can make database calls?
Thanks for any help. Been driving me mad!
CodePudding user response:
For orders added/updated through admin, use the code below
add_action('save_post_shop_order', 'backend_delegator', 10, 3);
function backend_delegator($post_id, $post, $update) {
// Orders in backend only
if (!is_admin())
return;
// Get an instance of the WC_Order
$order = new WC_Order($post_id);
//Fired when create a new order
if (!$update) {
$email = $order->get_billing_email();
}
if ($update) {
$email = $order->get_billing_email();
}
}
For orders placed from checkout, use the code below.
add_action('woocommerce_new_order', 'frondend_delegator', 10, 2);
function frondend_delegator($order_id, $order) {
$email = $order->get_billing_email();
}