Last active
April 28, 2023 08:33
-
-
Save mattiasghodsian/b473d5cd7762fd9d8588fb5122033f51 to your computer and use it in GitHub Desktop.
[Wordpress] Add profit to datalayer (gtm4wp)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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; | |
} |
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
Can you dump $dataLayer ?