Last order would be re-order in wooCommerce. How is it possible?



PHP Snippet 1:

function woo_reorder_scripts() {
    wp_enqueue_script('reorder', get_stylesheet_directory_uri().'/assets/js/reorder.js',array('jquery')); // js file from where we execute ajax request
    wp_localize_script( 'reorder', 'ajax_object', array( 'ajax_url' => admin_url( 'admin-ajax.php' ) )); // ajax
}
add_action('wp_enqueue_scripts','woo_reorder_scripts');

//Place following button where you want
function reorder_button() {
    if ( ! is_user_logged_in() ) return;
    echo '<a href="#" class="reorder">Reorder</a>';
}

//Our function executed from ajax
add_action( 'wp_ajax_reorder_action', 'reorder_action_callback' );

function reorder_action_callback() {
    $args = array(
        'limit'           => 1, // We want latest order
        'return'          => 'ids', // We want only the order ID
        'status'          => 'completed' // If we look for latest completed order or comment for any order status
    );
    $query = new WC_Order_Query( $args );
    $latest_order = $query->get_orders();
    if($latest_order) {
        foreach( $latest_order as $order_id ) {
            $order = wc_get_order( $order_id );
            if ( $order ) {
                $product_ids = array();
                foreach ( $order->get_items() as $item_id => $item ) {
                    if( has_term( array( 'tshirts' ), 'product_cat', $item->get_product_id() )) { // Change tshirts to category/ies you want
                        // WC()->cart->empty_cart(); // Uncomment if you want to clear cart before adding the items
                        WC()->cart->add_to_cart( $item->get_product_id(), $item->get_quantity()); // Add the order item with same quantity again
                    }
                }
            }
        }
    }
    exit();
}

PHP Snippet 2:

(function ($) {
    $(document).ready(function($) {

        $('.reorder').click(function(){
            $.ajax({
                type: 'POST'
                ,dataType: 'json'
                ,url: ajax_object.ajax_url
                ,data: {
                    'action': 'reorder_action'
                }
            });
        });
    });
})(jQuery);