How to add code below </head> on all pages for Facebook Pixels

Hi there,

I am setting up the Facebook pixel on https://hakubadigital.com

I have the pixel setup on the site using “Insert Headers & Footers” plugin.

But for the conversion event tracking I can’t work out how to add custom code for event tracking.

I searched the forum but only found old threads. Are you able to help with this??

I’d like to add

<script>
  fbq('track', 'ViewContent');
</script>

Just below the tag on all pages.

Hi There,

You have to setup a child theme first.

After that adding the following code under functions.php file locates in your child theme:

add_action( 'x_before_site_begin', 'print_script_before_site_begin' );
function print_script_before_site_begin(){
	?>	
	<script>
		fbq('track', 'ViewContent');
	</script>
	<?php
}

Let us know how it goes!

Hi Thai,

I have the Child Theme setup - thanks for this.

One more question: how can I adjust the code to only pull in certain phrases on specific pages?

eg

On “/TEST-ONE”
<script> fbq('track', 'TEST-ONE'); </script>

On “/TEST-TWO”
<script> fbq('track', 'TEST-TWO'); </script>

etc…

Thanks so much in advance!

Hi There,

In this case, please update the previous code to this:

add_action( 'x_before_site_begin', 'print_script_before_site_begin' );
function print_script_before_site_begin(){
	?>	
	<script>
		<?php if(is_page('test-one')){ ?>
			fbq('track', 'test-one');
		<?php } elseif (is_page('test-two')) { ?>
			fbq('track', 'test-two');
		<?php } ?>
	</script>
	<?php
}

The test-one , test-two should be your slug pages.

Hope it helps :slight_smile:

This is perfect - thank you!!

Glad to hear it!

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