首页 > 解决方案 > Embed a JS script WooCommerce on Thanyou page with Order data

问题描述

I need to create a script to send a query on the thank you page in woocommerce.

I am trying to do something similar for a shipping script But I nee to call an api with address and skus fired from the order thank you page. Can any of you help?

window.DeliverrApi.getShippingOptions({
    destination: {
        street1: "110 Sutter Street",
        street2: "9th Floor",
        zip: "94014",
        city: "San Francisco",
        state: "CA",
        country: "US"
    },
    skus: [
        "sku127"
    ],
    sellerId: "deliverr-seller"
})

there data:

https://tags.deliverr.dev/reference/#getshippingoptions

标签: javascriptphpwordpresswoocommerceorders

解决方案


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.


推荐阅读