Add Pinterest tracking code product line items product name and id to WooCommerce Checkout

357 Views Asked by At

I am hooking into the checkout thank you page. I'm stuck connecting the line_items to the Pinterest datalayer. I have the order total and order quantity working, but Pinterest still wants the Product ID. However because most orders contain multiple products I need to send an array of product names and ID's and this is where I get stuck.

//Hook pinterest tracking to Thank you on checkout

add_action( 'woocommerce_thankyou', 'rnr_pinterest_tracking', 1 );

function rnr_pinterest_tracking($order_id){ 
 
$order = wc_get_order( $order_id );
 
$order_total = $order->get_total();

$order_quantity = $order->get_item_count();

$line_items = $order->get_items();

foreach ( $line_items as $item ) {
    
    $product_id   = $item->get_product_id();
    
    $product = $order->get_product_from_item( $item );

// I think I need to assign the results of this to an array and
// output it in the pinterest tracking below.

}

//pinterest conversion tracking code
echo '<script>

pintrk("track", "checkout", {
value: '. $order_total. ',
order_quantity: ' . $order_quantity .' ,
currency: "USD",

//Need to put the line items here, as line items or a data layer?
  line_items []

// OR:
dataLayer = [{ 
items : [
  {
    product_id: '1414',
    product_category: 'Shoes'
  },
  {
    product_id: 'ABC',
    product_category: 'Toys'
  }
 ]
}];

} 

});
</script>';

}
1

There are 1 best solutions below

0
Vijay Hardaha On

Try this code:

function rnr_pinterest_tracking( $order_id ) {
    $order          = wc_get_order( $order_id );
    $order_total    = $order->get_total();
    $order_quantity = $order->get_item_count();
    $order_currency = $order->get_currency();

    $order_items_data = array();

    foreach ( $order->get_items() as $item_id => $item ) {
        $order_items_data[] = array(
            'product_id'       => $item->get_product_id(),
            'product_name'     => $item->get_name(),
            'product_price'    => $item->get_total(),
            'product_quantity' => $item->get_quantity(),
        );
    }

    printf(
        '<script>
        pintrk("track", "checkout", {
            value: %1$s,
            order_quantity: %2$s,
            currency: "%3$s",
            line_items: %4$s
        });
        </script>',
        esc_attr( $order_total ),
        esc_attr( $order_quantity ),
        esc_attr( $order_currency ),
        wp_json_encode( $order_items_data )
    );
}
add_action( 'woocommerce_thankyou', 'rnr_pinterest_tracking', 1 );