Viewing 1 replies (of 1 total)
  • Joseph,

    Not sure if you’re still working on this issue, but I thought I’d post an update in case anyone else searching for a solution comes across your post (as I did).

    I was searching for a way to include a Facebook Pixel script throughout a client website. I was having problems, as the Pixel code was sent to me within a script tag and included a noscript variant. I attempted to enqueue it as I normally do, saving the code within a .js file and referencing it via wp_enqueue_script in the theme functions file … but it wouldn’t work.

    //* Register Facebook Pixel script - DID NOT WORK
    add_action( 'wp_enqueue_scripts', 'register_facebook_pixel' );
    function register_facebook_pixel() {
    	wp_enqueue_script( 'facebook_pixel', get_bloginfo( 'stylesheet_directory' ) . '/js/facebook-pixel.js', null, '1.0.0', true );
    }

    Failed Facebook Pixel Injection

    However, after a little toying with it, I found I was able to make the injection work by escaping PHP within my function and directly inserting the Pixel script, rather than using wp_enqueue_script. The If statement conditionally inserts the code into all pages except those defined in the array.

    //* Register Facebook Pixel - WORKS!
    add_action( 'wp_enqueue_scripts', 'register_facebook_pixel' );
    function register_facebook_pixel() {
        if ( !is_page( array( 'forms', 'ordering', 'partner-with-us' ) ) ) { ?>
    		<!-- Facebook Pixel Code -->
    		<script>
    		!function(f,b,e,v,n,t,s){if(f.fbq)return;n=f.fbq=function(){n.callMethod?
    		n.callMethod.apply(n,arguments):n.queue.push(arguments)};if(!f._fbq)f._fbq=n;
    		n.push=n;n.loaded=!0;n.version='2.0';n.queue=[];t=b.createElement(e);t.async=!0;
    		t.src=v;s=b.getElementsByTagName(e)[0];s.parentNode.insertBefore(t,s)}(window,
    		document,'script','https://connect.facebook.net/en_US/fbevents.js');
    		fbq('init', '0000000000000000');
    		fbq('track', 'PageView');
    		</script>
    		<noscript><img height="1" width="1" style="display:none"
    		src="https://www.facebook.com/tr?id=0000000000000000&ev=PageView&noscript=1"
    		/></noscript>
    		<!-- DO NOT MODIFY -->
    		<!-- End Facebook Pixel Code -->
      	<?php }
    }

    Facebook Pixel Injection Success

    If anyone else comes across this post and has a better method of inserting script with noscript tags, please post, as I am following for updates!

    @josefism on Twitter

Viewing 1 replies (of 1 total)
  • The topic ‘How do I add noscript to enqueued scripts’ is closed to new replies.