WooCommerce ajax fetch order status

2019-09-20 18:04发布

My WooCommerce store will be updating the order status within a few minutes to a number of different states. Similar to how online pizza trackers work e.g. in the oven > baking > checking > delivering.

I'm currently displaying my order status on the thank you page -

<h3 class="order-status"><?php echo $order->status; ?></h3>

But I want to use ajax and possibly a jQuery set time out to update the status every 10 seconds.

setTimeout(fetchStatus, 10000);

I'm not sure what call to make will I have to create a function that uses the global $wooCommerce variable and keep updating it that way?

To confirm this is on a custom woocommerce thankyou page template.

1条回答
相关推荐>>
2楼-- · 2019-09-20 18:41

Here is a solution.

HTML

Change this <h3 class="order-status" id="order_status"><?php echo $order->status; ?></h3>.

AJAX Script

<script>
function fetchStatus()
{
    jQuery.ajax({
        url : '<?php echo site_url(); ?>/wp-admin/admin-ajax.php?action=fetch_order_status&order_id=<?php echo $order->get_order_number(); ?>',
        type : 'post',      
        error : function(response){
            console.log(response);
        },
        success : function( response ){
            jQuery('#order_status').text(response);
        }
    });
}

setInterval(fetchStatus, 1000);
</script>

functions.php

Add this to your theme's 'functions.php'.

function fetch_order_status(){
    $order = wc_get_order( $_REQUEST['order_id'] );
    $order_data = $order->get_data();
    echo $order_data['status'];
    die();
}

add_action('wp_ajax_nopriv_fetch_order_status', 'fetch_order_status');
add_action('wp_ajax_fetch_order_status','fetch_order_status');
查看更多
登录 后发表回答