I have this code in my product page after an item has been added to cart:
<script type="text/javascript>
//<![CDATA[
(function() {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
(document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(ga);
})();
var _gaq = _gaq || [];
_gaq.push(['_setCustomVar', 1, 'Page Type', 'Product', 3])
_gaq.push(['_setCustomVar', 2, 'Product Name', 'Gold Bracelet', 3]);
_gaq.push(['_trackEvent', 'Product Page', 'Added To Basket', 'Gold Bracelet', , 0]); // this is the line that isn't working.
_gaq.push(['_setAccount', 'UA-XXXXXXX-1']);
_gaq.push(['_trackPageview']);
//]]>
</script>
It seems the pageview is tracked, the two custom variables, but not the _trackEvent. Like I said in the title, if I copy and paste this code into Chrome Dev Console, the events show up just fine. I added an alert() to the code that returns the _trackPageview and it worked, so the JS is definitely getting parsed.
Any idea what i'm doing wrong?
Thank you
If the opt_value parameter isn't an integer (or undefined), the event won't be recorded.
Do you want this event to affect bounce rate calculations? If so, the opt_noninteraction can be left off since the default value is false:
_gaq.push(['_trackEvent', 'Product Page', 'Added To Basket', 'Bodysuit...']);
If you don't want the event to affect the bounce rate, use:
_gaq.push(['_trackEvent', 'Product Page', 'Added To Basket', 'Bodysuit...', undefined, true]);
I missed this in my first look at your code -- since _trackEvent is before _setAccount, the data it sends get's recorded to a default account (something like 'UA-XXXXX-X').
Move the _trackEvent call anywhere after _setAccount.
Also, since you've got both _trackEvent and _trackPageview in the same block of code, you'll want to be sure that the opt_noninteraction parameter is true.
Related
I've been struggling for a few days with this issue and I really hope you can help me out.
I've created a plugin, which is located in:
'/wp-content/plugins/my-cool-plugin'.
My plugin allows users to post a custom post type via a form on a public page, basically anyone should be able to post something.
Using jQuery, I listen to when my frontend form is submitted and using Ajax I pass the data from the form to a php file to process it into a post.
This file is located at:
'/wp-content/plugins/my-cool-plugin/inc/processor.php'.
Below is the content of my processor file:
$var1= $_POST['some'];
$var2= $_POST['data'];
$new_post = array(
'post_type' => 'my_custom_post',
'post_status' => 'publish',
'mcp_1' => $var1,
'mcp_2' => $var2
);
$post_id = wp_insert_post( $new_post, $wp_error );
if ($wp_error == 'false'){
$post_url = get_permalink( $post_id );
echo $post_url;
}else {
// some sort of error
}
When I test my form, it results in the following error:
Call to undefined function wp_insert_post() on line ... which is the following line:
$post_id = wp_insert_post( $new_post, $wp_error );
Do I need to include something since I'm not in the WordPress 'scope' anymore?
Or is there another (much better) way for inserting custom posts from a front end form?
Why are you running the file out of wordpress scope? That is not the best practive. Instead you could run it in wordpress scope and user wordpress native ajax.
add_action('wp_ajax_yourplugin_create_post', 'yourplugin_create_post');
add_action('wp_ajax_nopriv_yourplugin_create_post', 'yourplugin_create_post');
function yourplugin_create_post() {
// your code here
}
Then you would need your ajax url to be passed from php to js:
function your_plugin_ajaxurl() {
?>
<script type="text/javascript">
var yourPluginAjaxUrl = "<?php echo admin_url('admin-ajax.php'); ?>";
</script>
<?php
}
add_action('wp_head','your_plugin_ajaxurl');
Then you can use your ajax request but you would need to indicate action:yourplugin_create_post and url = yourPluginAjaxUrl
Try adding
require(dirname(__FILE__) . '/wp-load.php');
It took me some time to process Nick's answer, but I finally got it to work! Like Nick said, I dropped using the process file because is was out of the scope of WordPress. I moved my post creation from my proces file to a new function in the plugin init file (my-cool-plugin.php), as Nick suggested. This resulted in the following new function:
add_action('wp_ajax_coolplugin_create_post', 'coolplugin_create_post');
add_action('wp_ajax_nopriv_coolplugin_create_post', 'coolplugin_create_post');
function coolplugin_create_post() {
$var1 = $_POST['some'];
$var2 = $_POST['data'];
$new_post = array(
'post_type' => 'my_custom_post',
'post_status' => 'publish'
'post_title' => 'Some title'
);
$post_id = wp_insert_post( $new_post, $wp_error );
// check if there is a post id and use it to add custom meta
if ($post_id) {
update_post_meta($post_id, 'mcp_1', $var1);
update_post_meta($post_id, 'mcp_2', $var2);
}
if ($wp_error == false){
$post_url = get_permalink( $post_id );
echo $post_url;
}else {
// some sort of error
}
}
I also had to change the way I inserted my custom values into the newly created post, because the wp_insert_post() function only accepts default post parameters (see the wp_insert_post documentation for these parameters).
Next to my insert/create post function I also had to make some adjustments to my javascript file, which retrieves the filled in data from my form. Therefore (as Nick suggested) I needed to pass my Ajax URL from PHP to JS by adding the following function to my-cool-plugin.php like this:
function your_plugin_ajaxurl() { ?>
<script type="text/javascript">
var coolPluginAjaxUrl = "<?php echo admin_url('admin-ajax.php'); ?>";
</script>
<?php }
add_action('wp_head','your_plugin_ajaxurl');
By adding the coolPluginAjaxUrl variable to the head I'm able to use the URL in my javascript to post the data to when my form is submitted, like this:
$( '#form' ).on( 'submit', function(e) {
var request;
e.preventDefault();
var val_one = $( '#val-one' ).val();
var val_two = $( '#val-two' ).val();
var formData = {
action: 'coolplugin_create_post',
some: val_one,
data: val_two,
};
request = $.ajax({
type: 'POST',
url: coolPluginAjaxUrl,
data: formData,
});
});
The formData holds the coolplugin_create_post action defined in PHP and the request is posted to the coolPluginAjaxUrl URL, defined in the head.
Thanks Nick for pointing me into the right direction and I hope that my solution will also help others. Please note that I've stripped my code of several security measures for others to easily understand how the code works.
im really breaking my head with this one, so i hope anyone can take a look and help.
Im buildinf ajax-ed web page with pushState and fb comments. The problem is, that whenever i load new content and fb comments, i get an error about setting the href attribute.
Here is the code:
First, i async call fb init:
<script>
window.fbAsyncInit = function() {
FB.init({
appId : 'MY_APP_ID',
channelUrl : 'http://promplac.si/channel.php',
status : true,
cookie : true,
xfbml : true
});
};
(function() {
var e = document.createElement('script'); e.async = true;
e.src = document.location.protocol +'//connect.facebook.net/en_US/all.js';document.getElementById('fb-root').appendChild(e);
}());
</script>
On content change i call:
<script>
function showComment($currentUrl) {
document.getElementById('theplace').innerHTML='<fb:comments id="fbcomment" href="'+document.URL+'" width="510" num_posts="3"></fb:comments>';
console.log(document.getElementById('theplace').innerHTML);
FB.XFBML.parse();
console.log(document.getElementById('theplace').innerHTML);
}
</script>
HTML:
<div id="theplace" class="fb-comments"><fb:comments href="" numposts='3' height='150' id="fbcomment" width="510" num_posts="3"></fb:comments></div>
I made an example, i put in console.log the html for comments before and after FB.XFBML.parse() call. As you can see on this example: http://promplac.si/nagradne-igre/nagradna-igra/izberi-oblacila-v-vrednosti-200EUR/
The comments are normaly shown, but when you click on any other entry i get the warning about setting href attribute. But if you check the console, the href attribute is totaly OK? The effect doesnt happen when there is at least one comment...
Any idea what is wrong?
I have following script in my web site to push a custom variable to Google analytics. But even after 5 days this data is not appear in analytics. Can anyone notice something that I'm doing wrong here?
<!-- BEGIN GOOGLE ANALYTICS CODE -->
<script type="text/javascript">
//<![CDATA[
(function() {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
(document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(ga);
})();
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'xxxxxxxxxx']);
_gaq.push(['_trackPageview']);
_gaq.push(['_setCustomVar', 1, 'Product SKU','Test Data', 3]);
//]]>
</script>
<!-- END GOOGLE ANALYTICS CODE -->
Additional info : This script is from Google Analytis module for Magento, I'm over writing the _toHTML method in GA.php
The line that actually sets the custom variable comes after your _trackPageview() call, so the custom variable is never actually sent to the Analytics servers. You need to add either a _trackPageview() or _trackEvent() call after you set your custom variable(s).
_gaq.push(['_setAccount', 'xxxxxxxxxx']);
_gaq.push(['_trackPageview']);
_gaq.push(['_setCustomVar', 1, 'Product SKU','Test Data', 3]);
_gaq.push(['_trackEvent', 'Tow Truck', 'go', '-', 0, true]);
Here's some additional reference material on this: http://www.lunametrics.com/blog/2011/12/30/google-analytics-custom-variables-working/
Event tracking is not working with my Magento 1.5.0.1 CE installation. I have updated the code app/code/local/Mage/GoogleAnalytics/Block/GA.php to:
<!-- BEGIN GOOGLE ANALYTICS CODE v2 -->
<script type="text/javascript">
//<![CDATA[
var _gaq = _gaq || [];
' . $this->_getPageTrackingCode($accountId) . '
' . $this->_getOrdersTrackingCode() . '
_gaq.push(["_trackPageLoadTime"]);
(function() {
var ga = document.createElement(\'script\'); ga.type = \'text/javascript\'; ga.async = true;
ga.src = (\'https:\' == document.location.protocol ? \'https://ssl\' : \'http://www\') + \'.google-analytics.com/ga.js\';
(document.getElementsByTagName(\'head\')[0] || document.getElementsByTagName(\'body\')[0]).appendChild(ga);
})();
//]]>
</script>
<!-- END GOOGLE ANALYTICS CODE -->';
Then I added an event tracking link to my homepage:
LINK
So I tested this in firefox via firebug and the events are not working. Can someone please help a brother out?
Also the code is being inserted after the opening tag.
This is how it renders:
<!-- BEGIN GOOGLE ANALYTICS CODE v2 -->
<script type="text/javascript">
//<![CDATA[
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-XXXXXX-X']);
_gaq.push(['_trackPageview']);
(function() {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
(document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(ga);
})();
//]]>
</script>
<!-- END GOOGLE ANALYTICS CODE -->
Thanks!
You might not see it in Firebug because it executes so quickly. I would recommend testing via a proxy tool or the Live HTTP Headers plugin. See the tools recommended here.
Your syntax is correct.
Additionally, you may need to add a setTimeout() of 500ms or so to delay the click so that you don't encounter a race condition where the browser goes to that link prior to completing the execution of the tracking call. I have an example of this on a blog post I wrote:
LINK
I placed the google analytics code in my magento site 4 or 5 days ago, I think I have waited enough and that the report should be working.
However I still see Page Load Time as 0.00.
If you see the generated code from magento its like this:
My website is this
<!-- BEGIN GOOGLE ANALYTICS CODE -->
<script type="text/javascript">
//<![CDATA[
(function() {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
(document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(ga);
})();
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-XXXXXXXX-1']);
_gaq.push(['_trackPageview']);
_gaq.push(['_trackPageLoadTime']);
//]]>
</script>
<!-- END GOOGLE ANALYTICS CODE -->
I'm able to get _trackPageLoadTime to work just fine.
You can simulate it by editing the __utma cookie. The second period delimited value is the unique user ID. Just change the second to last digit to be 0, and it will track page load time for you.
Since ga.js is configured to only run for 10% of traffic, and only around 30% of users have browsers that support is, it'll usually only collect data from 3% of your users.