MarketPress and Google Tag Manager

Hi

I've been using MarketPress and Google Analytics Ecommerce Tracking successfully for a while. I've recently switched to using Google Tag Manager and now I don't see any Google Analytics Ecommerce Tracking data.

Could you point me in the right direction to get MarketPress and Google Tag Manager working?

Thanks
Pete

  • Bojan Radonic

    Hey there Pete,

    I have to be honest I never used Google Tag Manager so I'm not very experienced with it. I've found the following article regarding setting that up so you want to check it out first, you can find it here http://conversionxl.com/google-tag-manager/.

    Additionally since it is using Universal Analytics you might want to set that up in Products -> Store Settings -> General -> Google Analytics Ecommerce Tracking to Universal Analytics, see screenshot.

    Hope this helps :slight_smile:

    Best regards,
    Bojan

  • Bojan Radonic

    Hey again Pete,

    There is no direct integration with Google Tag Manager, I've used one of the chrome addons that checks for tags on specific pages and on some of them like single product pages it can't see any tags added which might be the reason this is not working so we would have to make modifications to the plugin in order for this to work which is is beyond the scope of support that we provide. See here : https://premium.wpmudev.org/manuals/using-wpmu-dev/support-vs-custom-development/

    Since this is an interesting I'll move this to features and feedback so other members can vote on it and if it proves to be popular we'll consider adding such integration in the future.

    Also, if you need to customize this then you can post a job in our job board where you can hire a developer to assist further:

    https://premium.wpmudev.org/wpmu-jobs/

    Best regards,
    Bojan

  • Earlyarts

    Hi Bojan

    Okay, perhaps you can give me some general advice instead.

    I've actually made some progress at outputting Google Tag Manager javascript to the checkout page, but I need some advice on hooking into Marketpress. The javascript needs to be written to the header (wp_header) and it needs only to fire after a successful purchase.

    I'm using this logic below to output the code.

    function write_marketpress_ecommerce_data_layer($order)
    {
    add_action( 'wp_head', 'add_marketpress_ecommerce_data_layer',10,1 );
    $_SESSION['order_arr']=$order;
    }
    
    function add_marketpress_ecommerce_data_layer($order)
    {
    	$order=$_SESSION['order_arr'];
    	// various logic to add the Google Analytics javascript using the $order data
    }
    add_action( 'mp_checkout_payment_pre_confirmation_' . $_SESSION['mp_payment_method'], write_marketpress_ecommerce_data_layer,10,1 );

    1) Is there a better way to structure this than calling one function from another - it seems clumsy.
    2) Is there a better way to pass the $order array to the add_marketpress_ecommerce_data_layer function rather than using a session. That seems clumsy also.

    If you could make a suggestion, I'd be grateful. If I make progress I'll post the code.

    Thanks
    Pete

  • Hoang Ngo

    Hi Pete,

    I hope you are well today.

    I think you can use only 1 hook wp_head for this, please check my example code here. Hope it can help :slight_smile:

    add_action('wp_head', 'display_google_tag_manager_code');
    function display_google_tag_manager_code()
    {
        global $wp_query;
        //check does the page is confirmation step (last step)
        if (!$wp_query->query_vars['checkoutstep'] == 'confirmation') {
            return;
        }
    
        //order still on session
        if (!isset($_SESSION['mp_order']) || empty($_SESSION['mp_order'])) {
            return;
        }
    
        global $mp;
        $order_id = $_SESSION['mp_order'];
        $order = $mp->get_order($order_id);
        if (!is_object($order)) {
            return ;
        }
    
        //javascript process code here
    }

    If you have any issues please don't hesitate to let us know so we can assist.

    Best regards,
    Hoang

  • Hoang Ngo

    Hi @Earlyarts,

    Perhaps I think something like this

    add_action('wp_head', 'display_google_tag_manager_code');
    function display_google_tag_manager_code()
    {
        global $wp_query;
        //check does the page is confirmation step (last step)
        if (!$wp_query->query_vars['checkoutstep'] == 'confirmation') {
            return;
        }
    
        //order still on session
        if (!isset($_SESSION['mp_order']) || empty($_SESSION['mp_order'])) {
            return;
        }
    
        global $mp;
        $order_id = $_SESSION['mp_order'];
        $order = $mp->get_order($order_id);
        if (!is_object($order)) {
            return ;
        }
    
        //javascript process code here
        ?>
        <script>
        <!-- Data layer for the tag manager -->
            dataLayer = [{
    
            }];
        </script>
        <!-- Google Tag Manager -->
    
        <!-- End Google Tag Manager -->
    <?php
    }

    Best regards,
    Hoang

  • Hoang Ngo

    Hi @Earlyarts,

    I hope you are well today and I'm sorry for the delay.

    Can you please try this for the MarketPress 3.x

    add_action( 'wp_head', 'display_google_tag_manager_code' );
    function display_google_tag_manager_code() {
    	if ( get_query_var( 'mp_order_id', 0 ) == 0 ) {
    		return;
    	}
    	//check does the page is confirmation step (last step)
    
    	$order_id = get_query_var( 'mp_order_id', 0 );
    
    	$order = new MP_Order( $order_id );
    
    	if ( ! $order->exists() ) {
    		return;
    	}
    
    	//javascript process code here
    	?>
    	<script>
    		<!-- Data layer for the tag manager -->
    		dataLayer = [{}];
    	</script>
    	<!-- Google Tag Manager -->
    
    	<!-- End Google Tag Manager -->
    	<?php
    }

    If you have any additional issues, please let us know and we'll be happy to help.

    Best regards,
    Hoang

  • Earlyarts

    Thanks, that's great, the code only appears upon order confirmation, which is exactly what I needed.

    I notice that the method of retrieving order data has changed. In the past I used things like
    $order->mp_shipping_total

    and others from the code below

    $js = '
    	<!-- Google Tag Manager -->
    	<script>
    	dataLayer=[{
    			"transactionId": "'.esc_attr($order->post_title).'",	// Transaction ID. PETE. Required.
    			"transactionAffiliation": "'.esc_attr(get_bloginfo('blogname')).'",	// Affiliation or store name.
    			"transactionTotal": '.$order->mp_order_total.',	// Grand Total.
    			"transactionShipping": "'.$order->mp_shipping_total.'",	// Shipping.
    			"transactionTax": "'.$order->mp_tax_total.'",	// Tax.
    		';
    	//loop the items
    	if (is_array($order->mp_cart_info) && count($order->mp_cart_info)) {
    	$js .= '"transactionProducts": [';
    		foreach ($order->mp_cart_info as $product_id => $variations) {
    			foreach ($variations as $variation => $data) {
    				$sku = !empty($data['SKU']) ? esc_attr($data['SKU']) : $product_id;
    				$js .= '{
    								 "id": "'.esc_attr($order->post_title).'", // Transaction ID. Required.
    								 "name": "'.esc_attr($data['name']).'",	// Product name. Required.
    								 "sku": "'.$sku.'",	// SKU/code.
    								 "category": "",	// Category or variation.
    								 "price": '.$data['price'].',	// Unit price.
    								 "quantity": '.$data['quantity'].'	// Quantity.
    							},';
    			}
    		}
    	$js=rtrim($js, ",")	;
    	$js .= ']}];';
    	$js .='
    	</script>
    	<!-- End Google Tag Manager -->';

    So can you tell me how best to get the order data using MarketPress v3?

    Thanks
    Pete

  • Hoang Ngo

    Hi Pete,

    I think you can try this

    $js = '
    	<!-- Google Tag Manager -->
    	<script>
    	dataLayer=[{
    			"transactionId": "' . esc_attr( $order->post_title ) . '",	// Transaction ID. PETE. Required.
    			"transactionAffiliation": "' . esc_attr( get_bloginfo( 'blogname' ) ) . '",	// Affiliation or store name.
    			"transactionTotal": ' . $cart->total() . ',	// Grand Total.
    			"transactionShipping": "' . $cart->shipping_total() . '",	// Shipping.
    			"transactionTax": "' . $cart->tax_total() . '",	// Tax.
    		';
    	//loop the items
    	if ( is_array( $cart->get_items() ) && count( $cart->get_items() ) ) {
    		$js .= '"transactionProducts": [';
    		foreach ( $cart->get_items_as_objects() as $product ) {
    			$sku = $product->get_meta( 'sku', $product->ID );
    			$js .= '{
    								 "id": "' . esc_attr( $order->post_title ) . '", // Transaction ID. Required.
    								 "name": "' . esc_attr( $product->post_title ) . '",	// Product name. Required.
    								 "sku": "' . $sku . '",	// SKU/code.
    								 "category": "",	// Category or variation.
    								 "price": ' . $product->get_price( 'lowest' ) . ',	// Unit price.
    								 "quantity": ' . $product->qty . '	// Quantity.
    							},';
    		}
    		$js = rtrim( $js, "," );
    		$js .= ']}];';
    		$js .= '
    	</script>
    	<!-- End Google Tag Manager -->';

    Let's see if that works for you :slight_smile:

    Best regards,
    Hoang

  • Earlyarts

    Hi @Hoang

    Thanks for that, I had to add
    $cart = $order->get_cart();
    so that the references to $cart would work

    Now it mostly works, thanks! Just a few questions

    1) For me $cart->shipping_total() returns &emdash
    Is this okay? So should I treat the value as a string?

    2) During repeated testing I found often the code didn't progress beyond

    if ( get_query_var( 'mp_order_id', 0 ) == 0 ) {
    		return;
    	}

    However if I started a new browser session, without the user logged in to the site, the code worked correctly every time.
    - will the code work correctly for logged in users?
    - will the code work correctly for repeat purchases (logged in or not)?

    Thanks
    Pete

  • Hoang Ngo

    Hi Pete,

    I hope you are well today.

    1) For me $cart->shipping_total() returns &emdash
    Is this okay? So should I treat the value as a string?

    This mean we don't have any shipping cost, you can check if that is mdash, we can display 0.
    For the #2, that code used for checking if a user on the complete page (after they finish the purchase). So it should work with or without user log in. The only condition is user need to be on the page after checkout.

    If you have any additional issues, please let us know and we'll be happy to help.

    Best regards,
    Hoang

  • Earlyarts

    Hi

    This code has stopped working for me. This part is the problem

    if ( get_query_var( 'mp_order_id', 0 ) == 0 ) {
    		return;
    	}

    I think the zero is now being returned as a string.

    I've modified the code to

    if ( get_query_var( 'mp_order_id', 0 ) == '0' ) {
    		return;
    	}

    and it works as expected.

    Is this okay to use? Is the value likely to change back to an integer in future releases?

    Pete

  • stripedrhino

    Earlyarts Hoang Ngo,

    Three Questions:

    1. I realize that I can determine the "key" (first half of this argument (transactionId,)) but where do I find the variables within MarketPress (2nd half)? (Also noted that a group at w3 is trying to put together a standard data object set for these "keys" here.)

    dataLayer=[{
    			"transactionId": "' . esc_attr( $order->post_title ) . '",

    I am trying to find a list of the variables that I can reference that are specifically associated with MarketPress (and all of WordPress for that matter.)

    2. Can we use a conditional statement similar to the below that would be placed above the Google Tag Manager container in the header?

    <?php
    if (is_page('/skype')) {?>
    DO SKYPE PAGE DATA LAYER
    <? } elseif (is_page('/checkout')) { ?>
    DO CHECKOUT DATA LAYER
    <? } else { ?>
    DO NOTHING
    <? } ?>

    3. Are you actually rewriting all the page templates throughout your site to put these dataLayers in place? What happens when you have to update a plugin that controls some of these pages, such as MarketPress? Or update WordPress, etc? I'm using a child theme, but it doesn't seem easy to maintain if we modify all the files.

    Thanks in advance.

  • Panos

    Hey there stripedrhino ,

    Sorry for the delay here and any troubles it may have caused you!

    Glad you have it all working, just some information about your previous questions:

    Question 1. How to get the variables.

    Before I continue on this, it might depend on the page you are at. For example if you are in the orders page ( after checkout by using the filter mp_order/header ) you will need to fetch the order :
    $order = new MP_Order( get_query_var( 'mp_order_id' ) );
    then you will need to get the cart:
    $cart = $order->get_meta( 'mp_cart_info' );
    and the products:
    $products = $cart->get_items_as_objects();
    For transaction info you can use:

    dataLayer.push({
                  'ecommerce': {
                    'purchase': {
                      'actionField': {
                        'id': '<?php echo $order->ID ?>',                         // Transaction ID. Required for purchases and refunds.
                        'affiliation': '<?php echo get_bloginfo('name'); ?>',
                        'revenue': '<?php echo $order->get_meta( 'mp_order_total' ); ?>',                     // Total transaction value (incl. tax and shipping)
                        'tax':'<?php echo $order->get_meta( 'mp_tax_total' ); ?>',
                        'shipping': '<?php echo $order->get_meta( 'mp_shipping_total' ); ?>'
                      },
                      'products': []
                    }
                  }
                });

    For products info you can make a loop:

    <?php foreach( $products as $product ){ ?>
    
                    <?php
                    $product = new MP_Product( $product->ID );
                    $sku = esc_attr( $product->get_meta( 'sku' ) );
                    $categories = array();
                    $terms = get_the_terms( $product->ID, 'product_category' );
                    if( ! empty( $terms ) ){
                        foreach( $terms as $term ){
                            $categories[] = $term->name;
                        }
                    }
    
                    ?>
    
                    ga_products.push({
                        'id':           '<?php echo $product->ID; ?>',                              // Transaction ID. Required
                        'name':         '<?php echo $product->title( false ); ?>',                  // Product name. Required
                        'sku':          '<?php echo !empty( $sku ) ? $sku : $product->ID; ?>',      // SKU/code
                        'category':     '<?php echo implode( ',', $categories ); ?>',               // Category or variation
                        'price':        '<?php echo $product->get_price( 'lowest' ); ?>',           // Unit price
                        'quantity':     '<?php echo $cart->get_item_qty( $product->ID ); ?>',        // Quantity
                        'brand': '',
                        'coupon' : ''
                    });
    
                <?php } ?>

    Question 2. Can you use conditional statement

    Yes. Not sure about the ones in your example, but you can use conditional statements and use different events for tag manager. Also you may need a to fetch orser, cart or product information in different ways depending on the page you are.

    Question 3.
    You can use hooks that are provided by WordPress ( wp_head, wp_footer ), or by theme, or by plugin ( eg in MarketPress mp_order/header )

    Cheers!

Thank NAME, for their help.

Let NAME know exactly why they deserved these points.

Gift a custom amount of points.