Tag manager e-commerce data layer - wordpress

Im using the google tag manager plugin for wordpress called: "DuracellTomi's Google Tag Manager". I enabled the e-commerce option on it. When i place a test order im forwarded to a custom thank you page. on that thank you page i enter the javascript console mode and there i type in "dataLayer" and this is the
output:
I expected something like this:
transactionId': '1234',
'transactionAffiliation': 'Acme Clothing',
'transactionTotal': 38.26,
'transactionTax': 1.29,
'transactionShipping': 5,
'transactionProducts': [{
'sku': 'DD44',
'name': 'T-Shirt',
'category': 'Apparel',
'price': 11.99,
'quantity': 1
},{
'sku': 'AA1243544',
'name': 'Socks',
'category': 'Apparel',
'price': 9.99,
'quantity': 2
what do i need to do to get the desired output?\
Edit:
My custom thank you page is set up like this:
// Redirect custom thank you
add_action( 'woocommerce_thankyou', 'bbloomer_redirectcustom');
function bbloomer_redirectcustom( $order_id ){
$order = new WC_Order( $order_id );
$url = 'http://dexport.nl/bedankt';
if ( $order->status != 'failed' ) {
wp_redirect($url);
exit;
}
}

I solved this problem myself.
The plugin doesnt asign the datalayer to the custom thank you page.
So there are 2 options.
You dont use a custom thank you page and use the default one. once you have done this you can go to your js console in developers tool and type in "data layer" you will get the desired result.
You use this plugin for a custom thank you page: https://wordpress.org/plugins/wc-custom-thank-you/

Related

Get details of product recently added to cart in WooCommerce and trigger a Google Analytics Add to Cart event

Goal- I am trying to run a Google Analytics Script using functions.php when a product is successfully added to the cart.
The problem -
Unable to get the details of the product added to the cart.
What I tried-
I tried to add the following code in functions.php to understand if I am getting the details properly. But the script doesn't seem to be working.
add_action('woocommerce_add_to_cart', 'custom_add_to_cart', 10, 6);
function custom_add_to_cart($cart_item_key,$product_id,$quantity,$variation_id,$variation,$cart_item_data
) {
?>
<script>
console.log("<?php echo 'Product ID ' . $product_id; ?>");
console.log("<?php echo 'Quantity ' . $quantity; ?>");
console.log("<?php echo 'Variation ID ' . $variation_id; ?>");
console.log("<?php echo 'Product ' . $variation; ?>");
console.log("<?php echo 'Cart Data ' . $cart_item_data; ?>");
</script>
<?php
}
If the problem is resolved- Once I get details successfully in console, I would pass the values in the following Google Analytics Script
gtag('event', 'add_to_cart', {
"items": [
{
"id": "P12345",//Will be replaced by product id
}
]
});
How I figured out the solution & how it worked for me
1. I figured out that whenever a product is added to the cart, the site is automatically redirected to the cart page.
2. Then I realized that the last added item gets added last in the item array, which made me use the cart page to trigger the add to cart instead of the cart page itself.
3. I used a Woocommerce hook available on the cart page, and then find the last item in the cart array.
4. Then I kind of ended and started the PHP script so that the Google Analytics event can be placed on the HTML.
5. Now I realized that some people can click on the cart and the cart page will still trigger the add to the cart item event. So I added a simple IF statement to run the google analytics event code only if the referrer is other than the cart page.
add_action( 'woocommerce_before_cart_contents', 'google_analytics_custom_add_to_cart');
function google_analytics_custom_add_to_cart() {
$prod_ids = array();
global $woocommerce;
$prods = $woocommerce->cart->get_cart();
$custom_last_item_index= count($prods)-1;
// loop products
foreach($prods as $p => $values) {
$product_detail = wc_get_product( $values['data']->get_id());
array_push($prod_ids, $product_detail->get_id());
}
?>
<script>
// understand the referrer
if(document.referrer!="https://websitename/cart/"){
gtag('event', 'add_to_cart', {
"items": [
{
"id": "<?php echo $prod_ids[$custom_last_item_index] ;?>",
}
]
});
}
</script>
<?php
}
It may not be the most straightforward or the best answer, but it did help me. Hence thought of sharing it with you all.

How to send dynamic values in dataLayer.push() method?

I am working on e-commerce website, where I am using Google Tag Manager(GTM) to analyse the data flow. So now I need to send some e-commerce booking data to GTM. For single cart value all looks ok. But when multiple cart values are there,I am not able to format the data-layer array how I am in need of. Below code works for single cart value, please help me to do the same for multiple cart items.
foreach($_SESSION['test']['item'] as $key => $value) {
dataLayer.push({
'event': 'Thankspage',
'itemname': [
{
'name': '<?php echo $_SESSION['test']['item']['item-name']; ?>',
'itemCode': '<?php echo $_SESSION['test']['item']['itemCode']; ?>',
'price': '<?php echo $_SESSION['test']['item']['item-price']; ?>'
}],
'totalprice': '<?php echo $_SESSION['test']['total-price']; ?>',
});
}
I tried using this foreach loop but i will get 'event': 'Thankspage' multiple times, i need structure like below if there are multiple items:
dataLayer.push({
'event': 'Thankspage',
'itemname': [
{
'name': 'Business Analysis Essentials',
'itemCode': 'BA-ESS',
'price': '1145.00'
},
{
'name': 'BABOK Foundation',
'itemCode': 'CGABAB3FCD',
'price': '595.00'
}],
'totalprice': '1740.00'
});
please help me in this regard.
The problem is that you are sending the dataLayer for every iteration of your for loop, what you need to do is create the array first and then send all of the data together. For example (code below not tested):
var itemsArray = []; //initialize empty array
var totalPrice; //initialize total price
foreach($_SESSION['test']['item'] as $key => $value) {
//code below will add all items in the itemsArray (no push to GTM yet)
itemsArray.push(
{
'name': '<?php echo $_SESSION['test']['item']['item-name']; ?>',
'itemCode': '<?php echo $_SESSION['test']['item']['itemCode']; ?>',
'price': '<?php echo $_SESSION['test']['item']['item-price']; ?>'
}
});
totalPrice = '<?php echo $_SESSION['test']['total-price']; ?>';
}
//once all items are in the itemsArray we will push the event to dataLayer
dataLayer.push({
'event': 'Thankspage',
'itemname': itemsArray,
'totalprice': totalPrice,
});

Which is exactly the right GA Ecommerce Tracking Code?

First, I want to say, I am new in code. Recently I find the Ecommerce Tracking is not working, of course missing Ecommerce Tracking code. I search a lot from Internet, still cannot figure out, who can help me, thanks a lot.
I find the follow code:
<script>
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new
Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','https://www.google-analytics.com/gtag.js','ga');
ga('create', 'UA-88888888-1', 'auto');
ga('send', 'pageview');
ga('require', 'ecommerce');
ga('ecommerce:addTransaction', {
'id': '1234', // Transaction ID. Required.
'affiliation': 'Fresh Egg', // Affiliation or store name.
'revenue': '43.66', // Grand Total.
'shipping': '3', // Shipping.
'tax': '1.29' // Tax.
});
ga('ecommerce:addItem', {
'id': '1234', // Transaction ID. Required.
'name': 'Fresh Egg', // Product name. Required.
'sku': 'AB12345', // SKU/code.
'category': 'Blue eggs', // Category or variation.
'price': '22.33', // Unit price.
'quantity': '1' // Quantity.
});
ga('ecommerce:send');
</script>
I donot know how to change the date, like, what "1234" means? Is this a certain date or something in from the code? And others! I know this may be a very foolish question, but I really need your help! Thanks a lot!
First of all, make sure ecommerce plugin is enough for what you need or maybe you should use enhanced ecommerce plugin.
You need to change, dynamically, each value depending on the transaction that is being executed.
It will depend on the programming language your site uses. For example, in php your code could be something like this:
ga('ecommerce:addItem', {
'id': '<?php echo $transacion_id; ?>',
'name': '<?php echo $product_name; ?>',
'sku': '<?php echo $sku; ?>',
'category': '<?php echo $product_category; ?>',
'price': '<?php echo $product_price; ?>',
'quantity': '<?php echo $product_quantity; ?>'
});
Consider using Google Tag Manager to implement your Analytics Ecommerce

WP REST-API create posts with custom fields generated by CPT

I used the CPT to create a post type UserQuestion with a few fields, such as ip_data. I want to be able to create one of this posts through API. So I looked into WP REST API .
However, the API offers /v2/user_question:
{
"title" : "test2",
"slug": "user_question",
"status": "publish",
"post_type": "user_question",
"meta": {
"ip" : "1111",
"question": "test question",
"answer": "yes, the answer"
}
}
The post is created, but it's not updating the customized fields data.
How should I make the request?
add_action("rest_insert_user_question", function (\WP_Post $post, $request, $creating)
{
$metas = $request->get_param("meta");
if (is_array($metas)) {
foreach ($metas as $name => $value) {
//update_post_meta($post->ID, $name, $value);
update_field($name, $value, $post->ID);
}
}
}, 10, 3);
In your functions.php (or in your plugin) add the above add_action and function. Change the 'user_question' in the add_action to match your post type, for example "rest_insert_portfolio" for a portfolio post type. Use update_field if you're using Advanced Custom Fields or update_post_meta if you're using regular custom fields.

How to add custom fields for WooCommerce order page (admin)?

I would like to add few input fields for the orders in WooCommerce/Wordpress. The fields will be only visible on the admin page. How to do that? Is it same like the pages/posts?
For the post types above I used add_post_meta. Is it the best way for that, or is there any hook for order fields?
Yes, just add_meta_box() to the post type shop_order and proceed as normal.
add_action( 'add_meta_boxes', 'add_meta_boxes' );
function add_meta_boxes()
{
add_meta_box(
'woocommerce-order-my-custom',
__( 'Order Custom' ),
'order_my_custom',
'shop_order',
'side',
'default'
);
}
function order_my_custom()
{
echo '<h1>Sample meta box</h1>';
}
Because you're asking specifically about WooCommerce, I'd like to expand on brasofilo's accepted answer by showing how you'd get the relevant WooCommerce order object (WC_Order) for the page the meta box is on.
Here's how you'd display the billing email from the order:
add_action('add_meta_boxes', function() {
add_meta_box('woocommerce-order-meta-24179529',
__( 'My Meta Box Title' ),
function() {
global $post;
// wc_get_order() returns one of bool|WC_Order|WC_Order_Refund
$order = wc_get_order($post->ID);
if($order instanceof WC_Order) {
echo "Billing email: ";
echo $order->get_billing_email();
}
},
'shop_order',
'side',
'default'
);
});

Resources