07967 325669 info@mootpoint.org

An important goal of a blog writer is to encourage comments on your posts. It is possible to set up Google Analytics to track comment posts as a goal, which will then allow you to analyse the source of new comments etc.

To track comment posts in Google Analytics, you need to send an event when the comment posting form is submitted. All of the solutions I have seen so far require one to add an onClick to the comment form submit button. For example:

<input name="submit" type="submit" onClick="ga('send', 'event', 'Comment', 'Submit');" id="submit" value="Post Comment" />;

Note that the code above is using the Universal Analytics event tracking format. If you are using the older ga.js script, you will need something like:

<input name="submit" type="submit" onClick="_gaq.push(['_trackEvent', 'Comment', 'Submit']);" id="submit" value="Post Comment" />;

This is fine if your theme uses a comment form template, but what if it uses the built-in WordPress comment_form function to generate the form? Open up your theme’s comments.php. If you can find a line like:

<?php comment_form(); ?>

then your theme is using the standard function. While it is easy to customise the various form fields using hooks, it is not possible to add an onClick to the submit button without making changes to /wp-includes/comment-template.php. Making changes to core WP files is bad practice as these can be overwritten by WordPress updates.

The solution is to bind the Google Analytics event to the form submit using jQuery. To do this, open your theme’s comments.php located at /wp-content/themes/your-theme-name/comments.php. My theme contained the following line which displays the comment form:

<?php if ( comments_open() ) { comment_form(); } ?>

I inserted a jQuery script to track a GA event when the form submit button is clicked:

	<?php if ( comments_open() ) { ?>
		jQuery(document).ready(function($) {
			$('#submit').on("click",function() {
				ga('send', 'event', 'Comment', 'Submit');
				console.log('onClick fired!');
	} ?>
    • For those not using Universal Analytics, replace line 5 above with:
				_gaq.push(['_trackEvent', 'Comment', 'Submit']);
  • To check if the event is firing correctly, go to a page with comments and open your browser developer console. Submit a test comment. You should see “onClick fired!” in the console log. Once you have confirmed it is working, you can delete line 6 above.