Embed a JS script WooCommerce on Thanyou page with Order data

Use the following to embed a JS for Deliverr in WooCommerce Order received page with the order details:

add_action( 'woocommerce_thankyou', 'deliverr_api_shipping_options_js' );
function deliverr_api_shipping_options_js( $order_id ) {
    // Get the WC_Order Object instance from order id
    $order     = wc_get_order( $order_id );

    $seller_id = 'deliverr-seller'; // ? !!! - to be defined

    $skus      = array(); // Initializing

    // Loop through order items
    foreach ( $order->get_items() as $item ) {
        $product = $item->get_product(); // Get the WC_Product Object instance
        $skus[]  = $product->get_sku(); // Add each product sku to the array
    }

    ?><script type="text/javascript">
    jQuery( function($){
        window.DeliverrApi.getShippingOptions({
            destination: {
                street1: "<?php echo $order->get_shipping_address_1(); ?>",
                street2: "<?php echo $order->get_shipping_address_2(); ?>",
                zip: "<?php echo $order->get_shipping_postcode(); ?>",
                city: "<?php echo $order->get_shipping_city(); ?>",
                state: "<?php echo $order->get_shipping_state(); ?>",
                country: "<?php echo $order->get_shipping_country(); ?>"
            }<?php if( ! empty($skus) ) { ?>,
            skus: [
                "<?php echo implode('", "', $skus); ?>"
            ]<?php }
            if( ! empty($seller_id) ) { ?>,
            sellerId: "deliverr-seller"
            <?php } ?>
        });
    });
    </script>
    <?php
}

Code goes in functions.php file of the active child theme (or active theme). Tested and works.

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top