Woocommerce Datalayer Implementation

31/07/2024
Datalayer for Woocommerce Featured Image

Datalayer Implementation by Functions.php

view_item_list Event

view_item_list event for category and archive pages. To implement view_item_list event use woocommerce_after_main_content hook.

<?php 
// view_item_list Datalayer

// Add SKU as data attribute
add_action('woocommerce_before_shop_loop_item_title', 'add_sku_to_product_html', 20);
function add_sku_to_product_html() {
    global $product;
    $sku = $product->get_sku();
    echo '<div class="product-sku" data-prod-sku="' . esc_attr($sku) . '"></div>'; 
}

add_action('woocommerce_after_main_content', 'view_item_list_datalayer', 10);
function view_item_list_datalayer() { 
	
    if (is_product_category()) {
	
        $category = get_queried_object();    
	
        $args = array(
            'post_type' => 'product',
            'posts_per_page' => -1,
            'tax_query' => array(
                array(
                    'taxonomy' => 'product_cat',
                    'field'    => 'id',
                    'terms'    => $category->term_id,
                ),
            ),
        );
        $query = new WP_Query($args);	
        $product_id = "";
	
        if ($query->have_posts()) {
            while ($query->have_posts()) {
                $query->the_post();
                $product_id = get_the_ID(); 
                $product_name = get_the_title();
            }
            wp_reset_postdata();
        } 
	?>

<script>
document.addEventListener("DOMContentLoaded", function() {
    let observer = new IntersectionObserver(entries => {
        let visibleItems = [];
        let hasVisibleItems = false;

        entries.forEach(entry => {		
            if (entry.isIntersecting) {
                let item = entry.target.closest('.product');
                let itemText = entry.target.textContent;
                let price = item.querySelector(".price").textContent;
                let brand = "Darwin's";
                let id = item.querySelector('a.quick-view').getAttribute('data-prod');
                let sku = item.querySelector('.product-sku').getAttribute('data-prod-sku');		
		
                let itemData = {
                    item_id:  sku,
                    item_name: itemText,
                    item_brand: brand,
                    item_list_id: "<?php echo esc_html($category->slug) ?>",
                    item_list_name: "<?php echo esc_html($category->name) ?>",
                    price: parseFloat(price.replace(/[₺,]/g, '')),
                    quantity: 1
                };
		
                visibleItems.push(itemData);
                hasVisibleItems = true;
                observer.unobserve(entry.target);
            }
        });
													
        if (hasVisibleItems) {
            dataLayer.push({ ecommerce: null });
            dataLayer.push({
                event: "view_item_list",
                ecommerce: {
                    item_list_id: "<?php echo esc_html($category->slug) ?>",
                    item_list_name: "<?php echo esc_html($category->name) ?>",
                    items: visibleItems
                }
            });
        }
    }, {
        threshold: 0.1 
    });

    document.querySelectorAll(".product-title").forEach(title => {
        observer.observe(title);
    });
});
</script><?php } }

view_item Event

view_item event for a single product page.

<?php

// view_item Datalayer
add_action( 'woocommerce_before_single_product_summary' , 'view_item', 5 );

function view_item() {
  global $product;
	
	if ( $product ) {
			$categories = $product->get_category_ids(); 
			if ( !empty( $categories ) ) {
			$category_names = array();

		   foreach ( $categories as $category_id ) {
				$category = get_term( $category_id, 'product_cat' );
				if ( ! is_wp_error( $category ) && ! empty( $category ) ) { 
                   $category_names[] = $category->name; 
               } 
		   } } 

		// Get Category Slugs
		$category_ids = $product->get_category_ids();
		$category_slugs = array();
		foreach ($category_ids as $category_id) {
		$category = get_term($category_id, 'product_cat');
		if ($category && !is_wp_error($category)) { $category_slugs[] = $category->slug; }}
} ?>
<script>
	jQuery(document).ready(function($) {

    // Function to check if the add_to_cart event is in the data layer
    function checkAddToCartEvent() {
        if (window.dataLayer) {
            for (var i = 0; i < window.dataLayer.length; i++) {
                var event = window.dataLayer[i];
                if (event.event === 'add_to_cart') { return true; }
            }
        }
        return false; }
            
		let variants = [];
		$('.variations select').each(function() {
			let label = $(this).closest('tr').find('th.label label').text().trim();
			let attributeName = $(this).closest('.variations tr').find('select').attr('data-attribute_name');
			let options = [];
			$(this).find('option').each(function() {
				let optionText = $(this).text().trim();
				if (optionText && optionText !== 'Bir seçim yapın') {options.push(optionText);}
			});
			let optionsText = options.join(', ');
			variants.push(attributeName.replace('attribute_', '') + ': ' + optionsText);
		});
		
		let brand = "Darwin's";
		
	if (!checkAddToCartEvent()) {
		dataLayer.push({ ecommerce: null });
		dataLayer.push({
			event: "view_item",
			ecommerce: {
			currency: "TRY",
			value: <?php echo $product->get_price() ?>,
			items: [
			{
			  item_id: "<?php echo $product->get_sku() ?>",
			  item_name: "<?php echo $product->get_name() ?>",
			  //affiliation: "",
			  //coupon: "",
			  discount: <?php echo ($product->get_regular_price() - $product-> get_sale_price() ) ?>,
			  //index: 0,
			  item_brand: brand,
			  item_category: "<?php echo $category_names[0] ?>",
			  item_category2: "<?php echo $category_names[1] ?>",
			  item_category3: "<?php echo $category_names[2] ?>",
			  item_category4: "<?php echo $category_names[3] ?>",
			  item_category5: "<?php echo $category_names[4] ?>",
			  item_list_id: "<?php echo end($category_slugs) ?>",
			  item_list_name: "<?php echo end($category_names) ?>",
			  item_variant: variants.join(', '),
			  //location_id: "ChIJIQBpAG2ahYAR_6128GcTUEo",
			  price: <?php echo $product->get_price() ?>,
			  quantity: 1 
				}]}});
	   }
	});
</script> 
<?php } ?>

It is not necessary for affiliation, coupon, index, and location_id, they are optional.

add_to_cart Event

For add_to_cart event on Woocommerce used woocommerce_add_to_cart hook.

<?php
// add_to_cart Datalayer
add_action( 'woocommerce_add_to_cart', function ()
{
	add_action( 'wp_footer', 'add_to_cart' );
	function add_to_cart(){ 
		global $product;
		//Product Category Array
		if ( $product ) {
    	$categories = $product->get_category_ids(); 
    	if ( !empty( $categories ) ) {
        $category_names = array();
        
        foreach ( $categories as $category_id ) {
            $category = get_term( $category_id, 'product_cat' );
            if ( ! is_wp_error( $category ) && ! empty( $category ) ) { 
              $category_names[] = $category->name; 
            } } } 
		
		//Get Category Slugs
		$category_ids = $product->get_category_ids();
		$category_slugs = array();
		foreach ($category_ids as $category_id) {
		$category = get_term($category_id, 'product_cat');
		if ($category && !is_wp_error($category)) { $category_slugs[] = $category->slug; }}}
		
		// Product Quantity in Current Order
		$quantity = isset($_POST['quantity']) ? intval($_POST['quantity']) : 1; 
        $brand = ""; //Add your brand name
		
?><script>	
	
	function printVariants() {
    const variants = [];
    const rows = document.querySelectorAll('table.variations tbody tr');
    
    rows.forEach(row => {
        const select = row.querySelector('td.value select');
        var nameAttribute = select.getAttribute('name');
		var label = nameAttribute.replace("attribute_", '');
        const selectedOptionText = select.options[select.selectedIndex].text;
        variants.push(label + ': ' + selectedOptionText);
    });
    
    return variants.join(', ');
}
	
dataLayer.push({ ecommerce: null });
dataLayer.push({
  event: "add_to_cart",
  ecommerce: {
    currency: "TRY",
     value: <?php echo floatval($product->get_price()) * floatval(esc_html($quantity)); ?>,
    items: [
    {
      item_id: "<?php echo $product->get_sku() ?>",
      item_name: "<?php echo $product->get_name() ?>",
      //affiliation: "",
      //coupon: "",
      discount: <?php echo ($product->get_regular_price() - $product-> get_sale_price() ) ?>,
      //index: 0,
      item_brand: "<?php echo $brand ?>",
      item_category: "<?php echo $category_names[0] ?>",
      item_category2: "<?php echo $category_names[1] ?>",
      item_category3: "<?php echo $category_names[2] ?>",
      item_category4: "<?php echo $category_names[3] ?>",
      item_category5: "<?php echo $category_names[4] ?>",
      item_list_id: "<?php echo end($category_slugs) ?>",
      item_list_name: "<?php echo end($category_names) ?>",
      item_variant: printVariants(),
      //location_id: "ChIJIQBpAG2ahYAR_6128GcTUEo",
      price: <?php echo $product->get_price() ?>,
      quantity: <?php echo esc_html($quantity) ?>
    }
    ]}
	});
</script>
<?php }}); ?>

view_cart Event

<?php
// view_cart Datalayer
add_action('woocommerce_cart_totals_after_order_total', 'view_cart');
function view_cart() { ?>

<script>	
   jQuery(document).ready(function($) {
        $.ajax({
            type: 'POST',
            url: '<?php echo admin_url('admin-ajax.php'); ?>',
            data: { action: 'view_cart' },
            success: function(response) {
                dataLayer.push({ ecommerce: null });
                dataLayer.push({
                    event: "view_cart",
                    ecommerce: {
                        currency: response.currency,
                        value: response.value,
                        items: response.items
                    }}); }}); }); 
</script><?php }

add_action('wp_ajax_view_cart', 'ajax_view_cart');
add_action('wp_ajax_nopriv_view_cart', 'ajax_view_cart');

function ajax_view_cart() {
    $items = array();
	
    foreach (WC()->cart->get_cart() as $cart_item) {
        $product = $cart_item['data'];
		
		$catnamelist = '' . wc_get_product_category_list($cart_item['product_id']) . '';
		$turncatnamelist = explode(",", $catnamelist);
		
		// Get Category Names 
		$category_names = [];
		
		// item_category 
		preg_match('~>(.*?)<~', $turncatnamelist[0], $output);
		$item_cat_1 = $output[1];
		if (!$item_cat_1 == null ) {array_push($category_names, $item_cat_1);}
		
		// item_category2
		preg_match('~>(.*?)<~', $turncatnamelist[1], $output);
		$item_cat_2 = $output[1];
		if (!$item_cat_2 == null ) {array_push($category_names, $item_cat_2);}
		
		// item_category3
		preg_match('~>(.*?)<~', $turncatnamelist[2], $output);
		$item_cat_3 = $output[1];
		if (!$item_cat_3 == null ) {array_push($category_names, $item_cat_3);}
		
		// item_category4
		preg_match('~>(.*?)<~', $turncatnamelist[3], $output);
		$item_cat_4 = $output[1];
		if (!$item_cat_4 == null ) {array_push($category_names, $item_cat_4);}
		
		// item_category5
		preg_match('~>(.*?)<~', $turncatnamelist[4], $output);
		$item_cat_5 = $output[1];
		if (!$item_cat_5 == null ) {array_push($category_names, $item_cat_5);}
		
		// Get Category Slugs
		$category_slugs = [];
		
		// category_slug
		preg_match('~category/(.*?)/"~', $turncatnamelist[0], $output);
		$item_slug_1 = $output[1];
		if (!$item_slug_1 == null ) {array_push($category_slugs, $item_slug_1);}
		
		// category_slug2
		preg_match('~category/(.*?)/"~', $turncatnamelist[1], $output);
		$item_slug_2 = $output[1];
		if (!$item_slug_2 == null ) {array_push($category_slugs, $item_slug_2);}
		
		// category_slug3
		preg_match('~category/(.*?)/"~', $turncatnamelist[2], $output);
		$item_slug_3 = $output[1];
		if (!$item_slug_3 == null ) {array_push($category_slugs, $item_slug_3);}
		
		// category_slug4
		preg_match('~category/(.*?)/"~', $turncatnamelist[3], $output);
		$item_slug_4 = $output[1];
		if (!$item_slug_4 == null ) {array_push($category_slugs, $item_slug_4);}
		
		// category_slug5 
		preg_match('~category/(.*?)/"~', $turncatnamelist[4], $output);
		$item_slug_5 = $output[1];
		if (!$item_slug_5 == null ) {array_push($category_slugs, $item_slug_5);}
		
		
		$variation = isset($cart_item['variation']) ? implode(', ', array_map(function($key, $value) {
                return $key . ': ' . $value;
            }, array_keys($cart_item['variation']), $cart_item['variation'])) : '';
		$get_variation = str_replace("attribute_", "", $variation);

        $brand = ""; //Add your brand name		

        $items[] = array(
			'item_id' => $product->get_id(),
			'item_name' => $product->get_name(),
			//'affiliation' => "",
			//'coupon' => "",
			'discount' => $product-> get_sale_price() > 0 ? ($product->get_regular_price() - $product-> get_sale_price() ) : 0,
			//'index' => 0,
			'item_brand' => 'Darwins',
			'item_category' => !empty($category_names[0]) ? $category_names[0] : "",
			'item_category2' => !empty($category_names[1]) ? $category_names[1] : "",
			'item_category3' => !empty($category_names[2]) ? $category_names[2] : "",
			'item_category4' => !empty($category_names[3]) ? $category_names[3] : "",
			'item_category5' => !empty($category_names[4]) ? $category_names[4] : "",
			'item_list_id' => end($category_slugs),
			'item_list_name' => end($category_names),
			'item_variant' => $get_variation,
			//'location_id' => "ChIJIQBpAG2ahYAR_6128GcTUEo",
			'price' => floatval($product->get_price()),
			'quantity' => $cart_item['quantity']
        );
    }

    wp_send_json(array(
        'currency' => 'TRY',
        'value' => WC()->cart->total,
        'items' => $items,
    )); }

 ?>

remove_from_cart Event

<?php
// remove_from_cart Datalayer
add_filter( 'woocommerce_cart_item_name', 'cart_item_category', 9999, 3 );
 
function cart_item_category( $name, $cart_item, $cart_item_key ) {
   $product = $cart_item['data'];
   if ( $product->is_type( 'variation' ) ) { $product = wc_get_product( $product->get_parent_id() ); }
   $cat_ids = $product->get_category_ids();
 
   if ( $cat_ids ) $name .= '<br>' . wc_get_product_category_list( $product->get_id(), ', ', '<div class="product-categories d-none">' . _n( 'Category:', 'Categories:', count( $cat_ids ), 'woocommerce' ) . ' ', '</div>' );
   return $name;
}

// Display selected product variant on the cart page with div tags
add_filter('woocommerce_get_item_data', 'display_selected_product_variant_with_div', 10, 2);
function display_selected_product_variant_with_div($item_data, $cart_item) {
	
    // Get product variation
    if (isset($cart_item['variation_id']) && $cart_item['variation_id'] != 0) {
        $product = wc_get_product($cart_item['variation_id']);
        $variation_attributes = $product->get_attributes();

        $variant_details = '<div class="selected-variant-details">';
        foreach ($variation_attributes as $attribute_name => $attribute_value) {
			if (!empty($attribute_value)) {
            $variant_details .= '<div class="variant-detail">';
            //$variant_details .= '<span class="variant-attribute-name">' . wc_attribute_label($attribute_name) . ' </span>';
            $variant_details .= '<p class="variant-attribute-value">' . $attribute_value . '</p>';
            $variant_details .= '</div>';
        }
			}
        $variant_details .= '</div>';

        $item_data[] = array(
            //'key'   => __('Selected Variants', 'woocommerce'),
            'key'   => __('', 'woocommerce'),
            'value' => $variant_details,
            'display' => $variant_details,
        );
    }
    return $item_data;
}


function add_d_none_css_on_cart_page() { if (is_cart()) {echo '<style>.d-none, dt.variation-, dd.variation- {display: none}</style>'; } }
add_action('wp_head', 'add_d_none_css_on_cart_page');

add_action( 'woocommerce_cart_totals_after_order_total', 'remove_from_cart_datalayer', 10, 2 );
function remove_from_cart_datalayer() { ?>
<script>
jQuery(document).ready(function($) {
	   $(document).on('click', '.remove', function(e) {
		   
var productId = $(this).data('product_id');
var sku = $(this).closest('.cart_item').find('.product-remove a').attr('data-product_sku');			   
var productName = $(this).closest('.cart_item').find('.product-name > a').text();
var value = $(this).closest('.cart_item').find('.product-subtotal bdi').text();
var price = $(this).closest('.cart_item').find('.product-price bdi').text();
var categoryArray = $(this).closest('.cart_item').find('.product-categories a').map(function() { return $(this).text(); }).get();
var hrefs = $(this).closest('.cart_item').find('.product-categories a').map(function() {return $(this).attr('href'); }).get();
var lasthreflink = hrefs[hrefs.length - 1];
var getslug = lasthreflink.match(/category\/([^\/]+)\//);	
var item_list_id = getslug[1];     
var variation = $(this).closest('.cart_item').find('.product-name .variation p').map(function() {return $(this).text();}).get().join(', ');
var quantity = $(this).closest('.cart_item').find('.product-quantity .quantity .input-text').val();
var brand = "Darwin's";		   
		   
		      dataLayer.push({ ecommerce: null });
				dataLayer.push({
				  event: "remove_from_cart",
				  ecommerce: {
					currency: "TRY",
					value: parseFloat(value.replace(/[₺,]/g, '')),
					items: [
					{
					  item_id: sku,
					  item_name: productName,
					  //affiliation: "",
					  //coupon: "",
					  //discount: 2.22,
					  //index: 0,
					  item_brand: brand,
					  item_category: categoryArray[0] ? categoryArray[0] : "",
					  item_category2: categoryArray[1] ? categoryArray[1] : "",
					  item_category3: categoryArray[2] ? categoryArray[2] : "",
					  item_category4: categoryArray[3] ? categoryArray[3] : "",
					  item_category5: categoryArray[4] ? categoryArray[4] : "",
					  item_list_id: item_list_id,
					  item_list_name: categoryArray[categoryArray.length - 1],
					  item_variant: variation,
					  //location_id: "ChIJIQBpAG2ahYAR_6128GcTUEo",
					  price: parseFloat(price.replace(/[₺,]/g, '')),
					  quantity: quantity }]}}); }); }); 
    </script> <?php }

begin_checkout Event

<?php 
// begin_checkout Datalayer
add_action('woocommerce_before_checkout_form', 'add_datalayer_script_to_checkout');

function add_datalayer_script_to_checkout() {
	
    if (is_checkout() && !is_order_received_page()) {
        $currency = get_woocommerce_currency();
        $cart = WC()->cart;
        $cart_total = $cart->total;
        $items = [];
        foreach ($cart->get_cart() as $cart_item) {
        $product = $cart_item['data'];
			
		$catnamelist = '' . wc_get_product_category_list($cart_item['product_id']) . '';
		$turncatnamelist = explode(",", $catnamelist);
		
		// Get Category Names 
		$category_names = [];
		
		// item_category 
		preg_match('~>(.*?)<~', $turncatnamelist[0], $output);
		$item_cat_1 = $output[1];
		if (!$item_cat_1 == null ) {array_push($category_names, $item_cat_1);}
		
		// item_category2
		preg_match('~>(.*?)<~', $turncatnamelist[1], $output);
		$item_cat_2 = $output[1];
		if (!$item_cat_2 == null ) {array_push($category_names, $item_cat_2);}
		
		// item_category3
		preg_match('~>(.*?)<~', $turncatnamelist[2], $output);
		$item_cat_3 = $output[1];
		if (!$item_cat_3 == null ) {array_push($category_names, $item_cat_3);}
		
		// item_category4
		preg_match('~>(.*?)<~', $turncatnamelist[3], $output);
		$item_cat_4 = $output[1];
		if (!$item_cat_4 == null ) {array_push($category_names, $item_cat_4);}
		
		// item_category5
		preg_match('~>(.*?)<~', $turncatnamelist[4], $output);
		$item_cat_5 = $output[1];
		if (!$item_cat_5 == null ) {array_push($category_names, $item_cat_5);}
		
		// Get Category Slugs
		$category_slugs = [];
		
		// category_slug
		preg_match('~category/(.*?)/"~', $turncatnamelist[0], $output);
		$item_slug_1 = $output[1];
		if (!$item_slug_1 == null ) {array_push($category_slugs, $item_slug_1);}
		
		// category_slug2
		preg_match('~category/(.*?)/"~', $turncatnamelist[1], $output);
		$item_slug_2 = $output[1];
		if (!$item_slug_2 == null ) {array_push($category_slugs, $item_slug_2);}
		
		// category_slug3
		preg_match('~category/(.*?)/"~', $turncatnamelist[2], $output);
		$item_slug_3 = $output[1];
		if (!$item_slug_3 == null ) {array_push($category_slugs, $item_slug_3);}
		
		// category_slug4
		preg_match('~category/(.*?)/"~', $turncatnamelist[3], $output);
		$item_slug_4 = $output[1];
		if (!$item_slug_4 == null ) {array_push($category_slugs, $item_slug_4);}
		
		// category_slug5 
		preg_match('~category/(.*?)/"~', $turncatnamelist[4], $output);
		$item_slug_5 = $output[1];
		if (!$item_slug_5 == null ) {array_push($category_slugs, $item_slug_5);}
			
		// Get Product Variations	
		$variation = isset($cart_item['variation']) ? implode(', ', array_map(function($key, $value) {
                return $key . ': ' . $value;
            }, array_keys($cart_item['variation']), $cart_item['variation'])) : '';
		$get_variation = str_replace("attribute_", "", $variation);	
        $brand = ""; //Add your brand name
			
            $items[] = [
                'item_id' => $product->get_sku(),
                'item_name' => $product->get_name(),
                //'affiliation' => '',
                'coupon' => $cart_item['applied_coupons'] ? $cart_item['applied_coupons'][0] : '',
                'discount' => $cart_item['line_subtotal'] - $cart_item['line_total'],
                //'index' => 0,
                'item_brand' => $brand,
                'item_category' => !empty($category_names[0]) ? $category_names[0] : "",
				'item_category2' => !empty($category_names[1]) ? $category_names[1] : "",
				'item_category3' => !empty($category_names[2]) ? $category_names[2] : "",
				'item_category4' => !empty($category_names[3]) ? $category_names[3] : "",
				'item_category5' => !empty($category_names[4]) ? $category_names[4] : "",
				'item_list_id' => end($category_slugs),
				'item_list_name' => end($category_names),
                'item_variant' => $get_variation,
                //'location_id' => '',
                'price' => $cart_item['line_total'],
                'quantity' => $cart_item['quantity']
            ];
        }
        ?>
<script>
  dataLayer.push({ ecommerce: null });
  dataLayer.push({
    event: "begin_checkout",
    ecommerce: {
        currency: "<?php echo $currency; ?>",
        value: <?php echo $cart_total; ?>,
        coupon: "<?php echo $cart->get_applied_coupons() ? $cart->get_applied_coupons()[0] : ''; ?>",
        items: <?php echo json_encode($items); ?>
    }
  });
</script>
<?php }}?>

add_payment_info Event

<?php 
// add_payment_info Datalayer
function is_page_slug_part($slug_part) {
    if (is_page()) {
        $current_url = $_SERVER['REQUEST_URI'];
        if (strpos($current_url, $slug_part) !== false) {return true;}
    }
    return false;
}

add_action('wp_footer', function () {
	if (is_page_slug_part('/order-pay/')) {
	  if (is_checkout()) {
        
		$chosen_gateway = WC()->session->get('chosen_payment_method');
		$gateway_title = '';
		if ($chosen_gateway) {
		$available_gateways = WC()->payment_gateways->get_available_payment_gateways();
		if (isset($available_gateways[$chosen_gateway])) {
          $gateway_title = $available_gateways[$chosen_gateway]->get_title();
          }
		}

		$currency = get_woocommerce_currency();
        $cart = WC()->cart;
        $cart_total = $cart->total;
		 
		$brand = ""; //Add your brand name  
    	?>
<script>
   dataLayer.push({ ecommerce: null }); 
   dataLayer.push({
    event: "add_payment_info",
    ecommerce: {
    currency: "<?php echo $currency; ?>",
    value: <?php echo $cart_total; ?>,
    coupon: "<?php echo $cart->get_applied_coupons() ? $cart->get_applied_coupons()[0] : ''; ?>",
    payment_type: "<?php echo esc_html($gateway_title); ?>",
    items: [
    <?php 
       foreach ($cart->get_cart() as $cart_item) :
       $product = $cart_item['data'];
		  
       $catnamelist = '' . wc_get_product_category_list($cart_item['product_id']) . '';
       $turncatnamelist = explode(",", $catnamelist);

       // Get Category Names 
       $category_names = [];

       // item_category 
       preg_match('~>(.*?)<~', $turncatnamelist[0], $output);
       $item_cat_1 = $output[1];
       if (!$item_cat_1 == null ) {array_push($category_names, $item_cat_1);}

       // item_category2
       preg_match('~>(.*?)<~', $turncatnamelist[1], $output);
       $item_cat_2 = $output[1];
       if (!$item_cat_2 == null ) {array_push($category_names, $item_cat_2);}

		// item_category3
		preg_match('~>(.*?)<~', $turncatnamelist[2], $output);
		$item_cat_3 = $output[1];
		if (!$item_cat_3 == null ) {array_push($category_names, $item_cat_3);}

        // item_category4
        preg_match('~>(.*?)<~', $turncatnamelist[3], $output);
        $item_cat_4 = $output[1];
        if (!$item_cat_4 == null ) {array_push($category_names, $item_cat_4);}

		// item_category5
		preg_match('~>(.*?)<~', $turncatnamelist[4], $output);
		$item_cat_5 = $output[1];
		if (!$item_cat_5 == null ) {array_push($category_names, $item_cat_5);}

		// Get Category Slugs
		$category_slugs = [];

		// category_slug
		preg_match('~category/(.*?)/"~', $turncatnamelist[0], $output);
		$item_slug_1 = $output[1];
		if (!$item_slug_1 == null ) {array_push($category_slugs, $item_slug_1);}

		// category_slug2
		preg_match('~category/(.*?)/"~', $turncatnamelist[1], $output);
		$item_slug_2 = $output[1];
		if (!$item_slug_2 == null ) {array_push($category_slugs, $item_slug_2);}

		// category_slug3
		preg_match('~category/(.*?)/"~', $turncatnamelist[2], $output);
		$item_slug_3 = $output[1];
		if (!$item_slug_3 == null ) {array_push($category_slugs, $item_slug_3);}

		// category_slug4
		preg_match('~category/(.*?)/"~', $turncatnamelist[3], $output);
		$item_slug_4 = $output[1];
		if (!$item_slug_4 == null ) {array_push($category_slugs, $item_slug_4);}

		// category_slug5 
		preg_match('~category/(.*?)/"~', $turncatnamelist[4], $output);
		$item_slug_5 = $output[1];
		if (!$item_slug_5 == null ) {array_push($category_slugs, $item_slug_5);}
		  
		// Get Product Variations	
		$variation = isset($cart_item['variation']) ? implode(', ', array_map(function($key, $value) {
				return $key . ': ' . $value;
				}, array_keys($cart_item['variation']), $cart_item['variation'])) : '';
		$get_variation = str_replace("attribute_", "", $variation);	
		  
		$item_data = [
			'item_id' => $product->get_sku(),
			'item_name' => $product->get_name(),
			//'affiliation' => '',
			'coupon' => $cart_item['applied_coupons'] ? $cart_item['applied_coupons'][0] : '',
			'discount' => $cart_item['line_subtotal'] - $cart_item['line_total'],
			//'index' => '',
			'item_brand' => $brand,
			'item_category' => !empty($category_names[0]) ? $category_names[0] : "",
			'item_category2' => !empty($category_names[1]) ? $category_names[1] : "",
			'item_category3' => !empty($category_names[2]) ? $category_names[2] : "",
			'item_category4' => !empty($category_names[3]) ? $category_names[3] : "",
			'item_category5' => !empty($category_names[4]) ? $category_names[4] : "",
			'item_list_id' => end($category_slugs),
			'item_list_name' => end($category_names),
      		'item_variant' => $get_variation,
			//'location_id' => 'ChIJIQBpAG2ahYAR_6128GcTUEo',
			'price' => $cart_item['line_total'],
			'quantity' => $cart_item['quantity']
        ];
            echo json_encode($item_data) . ',';
            endforeach; ?>
                ]
			  }
			});
</script>  	
<?php }}}); ?>

purchase Event

<?php
// purchase Datalayer
function purchase_datalayer($order_id) {
  $order = wc_get_order($order_id);
  if (!$order) return; ?>
  <script>
     dataLayer.push({ ecommerce: null });
     dataLayer.push({
		 event: "purchase",
		 ecommerce: {
			 transaction_id: "<?php echo $order->get_id(); ?>",
			 value: <?php echo $order->get_total(); ?>,
			 tax: <?php echo $order->get_total_tax(); ?>,
			 shipping: <?php echo $order->get_shipping_total(); ?>,
			 currency: "<?php echo get_woocommerce_currency(); ?>",
			 coupon: "<?php echo implode(', ', $order->get_used_coupons()); ?>",
			 items: [
				 <?php foreach ($order->get_items() as $item_id => $item) :
					$product = $item->get_product();	

					// Get Product Variants
					$get_variants_meta_data = $item->get_meta_data(); 
					$formatted_meta_variants = array();
					foreach ($get_variants_meta_data as $meta) {
                       $formatted_meta_variants[] = $meta->key . ': ' . $meta->value;
                    }
					$variants = implode(', ', $formatted_meta_variants);

					// Get Product Categories
					$categories = array();
					$product_id = $item->get_product_id();
					$product = wc_get_product($product_id);
					if ($product) {
						$product_categories = wp_get_post_terms($product_id, 'product_cat');
						foreach ($product_categories as $category) {
							if (!in_array($category->name, $categories)) {
								$categories[] = $category->name;
							}
						}
					}
					// Get Product Category Link & Slug for list_item_id
					$links = array();
					if ($product) {
						$product_categories = wp_get_post_terms($product_id, 'product_cat');
						foreach ($product_categories as $category) {	
							if (!in_array($category->term_id, $links)) {
                             $links[] = get_term_link($category->term_id, 'product_cat');
                            }
						} 
					}
					preg_match('/category\/([^\/]+)\/$/', end($links), $category_slug);
					$item_list_id = $category_slug[1];
					
					$item_brand = ""; //Write you brand name	

					$item_data = [
						'item_id' => $product->get_sku(),
						'item_name' => $product->get_name(),
						//'affiliation' => '',
						'coupon' => implode(', ', $order->get_used_coupons()),
						'discount' => ($product->get_regular_price() - $product-> get_sale_price() ),
						//'index' => '',
						'item_brand' => $item_brand,
						'item_category' => !empty($categories[0]) ? $categories[0] : "",
						'item_category2' => !empty($categories[1]) ? $categories[1] : "",
						'item_category3' => !empty($categories[2]) ? $categories[2] : "",
						'item_category4' => !empty($categories[3]) ? $categories[3] : "",
						'item_category5' => !empty($categories[4]) ? $categories[4] : "",
						'item_list_id' => $item_list_id,
						'item_list_name' => end($categories),
						'item_variant' => $variants,
						//'location_id' => 'ChIJIQBpAG2ahYAR_6128GcTUEo',
						'price' => $item->get_total(),
						'quantity' => $item->get_quantity(),
					];
					echo json_encode($item_data) . ',';
					endforeach; ?>
                ]}});
  </script>
  <?php }

add_action('woocommerce_thankyou', 'purchase_datalayer', 10, 1);
?>