skip to Main Content
WordPress Inject Javascript To Footer Using Action

WordPress inject Javascript to footer using action

Many times we need to Inject Javascript into the post detail page. When we want to track how many users visit the post detail page at that time we need to Inject Js code into the WordPress Post Single. I used Facebook Pixel and Google Tag Manager for tracking the visits to the WordPress Post detail page.

So, Today we learn how we can inject Facebook Pixel Code when any user visits post detail page.

We use “wp_footer” action for injecting Facebook Pixel code in the WordPress footer. WordPress allows creating custom Js code using “wp_footer” action.

Let’s see how we can inject Facebook Pixel code for tracking the ViewContent event.

function track_facebook_pixel() {
    if( is_single() ){
    ?>
    <script type="text/javascript">
    (function($){
        $(document).ready(function(){
            fbq('track', 'ViewContent', 'Post');
        });
    })(jQuery);
    </script>
    <?php
    }
}
add_action( 'wp_footer', 'track_facebook_pixel');

I am adding ViewContent Facebook Pixel Event because I want to track How many users visit the post detail page. instead of the home page.

If you face any issue with Injecting the JS code using “wp_footer” Hook write the comment below.

 

Saroj

I am a web designer and developer part-time blogger. Write something on some free time. Find my every day thought here :)

Leave a Reply

Your email address will not be published. Required fields are marked *

Back To Top