Adding custom javascript to global header

Hello THEMECO Team,

I have searched the forum and cannot find the answer to my specific challenge.

I need to add this custom javascript to the global header section of a client’s website, in order for Google Analytics to track the instances of visitors successfully submitting a message through the contact form. From Contact Form 7 Support (from https://contactform7.com/tracking-form-submissions-with-google-analytics/):

The final step is inserting this JavaScript code snippet into the HTML header () of each page. You can edit your theme’s header.php template, or you can use wp_head action hook from the theme’s functions.php.

You of course need to wrap the code with tag when you embed script code into HTML:

<script>
document.addEventListener( 'wpcf7mailsent', function( event ) {
    ga('send', 'event', 'Contact Form', 'submit');
}, false );
</script>

If you have set up everything correctly, Google Analytics will track successful form submissions through contact forms as an event with “Contact Form” as the event category, and “submit” as the event action.

I thought that it might be as simple as entering the script (sans script tags) into the custom global javascript in the Customizer, but I am not really sure if this will work. I have placed it there for now, but when I inspect the site, I do not see this script in the head section of the site. Can you please advise me of the best way to get this code where it needs to be? Custom global javascript in Customizer? Add as an action in functions.php of a child theme? Add into header.php? Please be detailed in your response.

Website: http://www.organizedbyellis.com/
I have entered the login credentials in a secure note.

Thank you!
Rayna

Hi There,

Please add the following code under functions.php file locates in your child theme:

add_action( 'wp_head', 'print_google_conversion_script', 999 );
function print_google_conversion_script(){
	?>
	<script>
	document.addEventListener( 'wpcf7mailsent', function( event ) {
	    ga('send', 'event', 'Contact Form', 'submit');
	}, false );
	</script>
	<?php
}

Thank you! I’ve added the code and I will check GA in 24-48 hours to make sure it is working :slight_smile:

No problem at all - please do keep us updated :slight_smile:

This topic was automatically closed 10 days after the last reply. New replies are no longer allowed.