Woocommerce Get Orders on Thank you page and pass data javascript snippet

后端 未结 1 1678
轮回少年
轮回少年 2020-12-03 19:24

I am trying to read from thankyou.php orders and populate order_id, sku, price, quantity to a javascript snipper. The problem for me is how to \"catch\" the

相关标签:
1条回答
  • 2020-12-03 19:46

    UPDATED
    As you are finding hard to locate functions.php file you can created a plugin. Create a PHP file as wh-thankyou-tracking.php under /wp-content/plugins/ and copy paste the below code to it and save it. And form admin panel Activate WH Order Tracking JS plugin

    <?php
    /**
     * Plugin Name: WH Order Tracking JS
     * Version: 0.1
     * Description: This plugin will add a JS tracking code to WooCommerce Thankyou page.
     * Author: Raunak Gupta
     * Author URI: https://www.webhat.in/
     * Text Domain: wh
     */
    if (!defined('ABSPATH'))
    {
        exit;
    } // Exit if accessed directly
    
    if (!class_exists('WooCommerce'))
    {
        exit;
    }// Exit if WooCommerce is not active
    
    function wh_CustomReadOrder($order_id)
    {
        //getting order object
        $order = wc_get_order($order_id);
    
        $items = $order->get_items();
        $product_js = [];
    
        foreach ($items as $item_id => $item_data)
        {
            //getting product object
            $_product = wc_get_product($item_data['item_meta']['_product_id'][0]);
    
            //getting all the product category
            $pro_cat_array = wp_get_post_terms($_product->ID, 'product_cat');
    
            $sku = $sku = $_product->get_sku();
            $qty = $item_data['item_meta']['_qty'][0];
            $pro_cat = implode(',', $pro_cat_array);
            $pro_brand = $_product->get_attribute('pa_brand'); //replace it with your brand attribute slug
            $pro_price = $item_data['item_meta']['_line_total'][0];
    
            //storing all the line item as a string form
            $product_js[] = '{id: "' . $sku . '",category:"' . $pro_cat . '",brand:"' . $pro_brand . '",price: "' . $pro_price . '"quantity:"' . $qty . '"}';
        }
    
        ?>
        <script type="text/javascript">
            order.purchase = {
                currency: 'EUR',
                transactionId: '<?= $order->id ?>',
                products: [<?= implode(',', $product_js) ?>]
            };
        </script>
        <?php
    }
    
    add_action('woocommerce_thankyou', 'wh_CustomReadOrder');
    

    Hope this helps!

    0 讨论(0)
提交回复
热议问题