How do I insert JS tracking code to a page with the WP editor?

My client needs to add unique blocks of javascript to certain pages in order to track visitors. How do I go about doing this?

At first I tried to use a custom field but the field stripped out everything before outputting it to the page so I got an empty result. Then I installed an Advanced Custom Fields extension that allows you to add code to your page and then call it on the template but it put the code within script tags which breaks the tracking code.

Read More

So I’m at a bit of a loss right now.

Related posts

3 comments

  1. Use conditional tags.

    Change the 5th parameter to load in the footer.

    Change get_stylesheet_directory_uri() to get_template_directory_uri() for use in parent themes.

    add_action( 'wp_enqueue_scripts', 'add_tracking_scripts' );
    
    function add_tracking_scripts() {
    if ( is_page('slug') ) {
    wp_register_script(
        'tracking-script',
        get_stylesheet_directory_uri() . '/tracking-script.js',
        false,
        '1.0',
        true
    );
    
    wp_enqueue_script( 'tracking-script' );
        }
    }
    

    Source http://codex.wordpress.org/Function_Reference/wp_enqueue_script

  2. You could use conditional statements to put it in the footer of the page. Find the numerical identifiers of the appropriate pages, then go to Appearance > Editor and edit your themes footer.php

    <?php
    if (is_page ('XX')) { ?>
    // tracking code here for page XX
    <?php
    } elseif (is_page ('YY')) { ?>
    // tracking code for another page YY
    
    <?php
    } 
    ?>
    

    etc.

  3. You were on the right track before. Advanced Custom Fields is great for this, although you could use any method to add a metabox to a post/page/custom post type.

    Add a textarea metabox, and insert your tracking code. If you are using ACF, make sure you set the “Formatting” field to “No Formatting”.

    In your theme, you can simply write a little conditional code in your header/footer:

    <html>
    <head>
    <!-- all your header code -->
    <?php if($code_to_insert = get_field('your_field_name_in_ACF')) { ?>
    <?php echo $code_to_insert; ?>
    <?php }; ?>
    </head>
    

    Just make sure you include the tags in your code. This should only place the code in the page if the page contains something in the metabox. Of course – this isn’t sanity checking what you’re inserting in any way, and potentially this could break your pages if someone plugs bad code in there. 🙂

    The better way would be to write a function, include the function in your template, and use metadata (custom field) to enable it. But that’s a bit more work. What I described above is very easy if you’re using ACF.

    Good luck!

Comments are closed.