Skip to content

Instantly share code, notes, and snippets.

@mattiasghodsian
Last active April 28, 2023 08:33
Show Gist options
  • Save mattiasghodsian/b473d5cd7762fd9d8588fb5122033f51 to your computer and use it in GitHub Desktop.
Save mattiasghodsian/b473d5cd7762fd9d8588fb5122033f51 to your computer and use it in GitHub Desktop.
[Wordpress] Add profit to datalayer (gtm4wp)
/**
* Requires Plugin: Google Tag Manager for Wordpress & WooCommerce Cost of Goods
* Author: Mattias Ghodsian
* Donate a cup of coffee: https://www.buymeacoffee.com/mattiasghodsian
* Donate Eth: 0xBBB96204E45D11C9799c6B12E6eE6F0d4A071Ef5
*/
function gtm4wp_add_profit_datalayer_data( $dataLayer ){
if ( is_order_received_page() ){
$orderID = $dataLayer['ecommerce']['purchase']['actionField']['id'];
$orderItems = $dataLayer['ecommerce']['purchase']['products'];
if ( $orderID && $orderItems ) {
$total_price = 0;
foreach ($orderItems as $key => $item) {
$productID = get_product_by_sku( $item['sku'] );
if ( $productID !== false) {
$buyPrice = get_post_meta( $productID, '_wc_cog_cost', true);
if ( $buyPrice ) {
$total_price = $total_price + ($buyPrice * $item['quantity']);
}
}
}
// $dataLayer["ecomm_profit"] = ( $dataLayer['ecomm_totalvalue'] - $total_price );
$dataLayer["ecomm_profit"] = ( $dataLayer['ecommerce']['purchase']['actionField']['revenue'] - $total_price );
}
}
return $dataLayer;
}
add_filter( 'gtm4wp_compile_datalayer', 'gtm4wp_add_profit_datalayer_data' , 20);
/**
* Get product by SKU
**/
function get_product_by_sku( $sku ) {
global $wpdb;
$product_id = $wpdb->get_var( $wpdb->prepare( "SELECT post_id FROM $wpdb->postmeta WHERE meta_key='_sku' AND meta_value='%s' LIMIT 1", $sku ) );
if ( $product_id ) {
return $product_id;
}
return false;
}
@erikmolenaarnl
Copy link

erikmolenaarnl commented Apr 16, 2021

Hi Mattias,

Sorry for my late reply.
I have set up a fresh install of:

WordPress 5.7.1
Woocommerce 5.2.2
GTM4WP 1.12.2

I am still getting the same error, $dataLayer is empty.
Screenshot: https://www.screencast.com/t/dxUxj0loNC

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment