1

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.

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

  • Why do you need to execute the code within the content area? Why not load it in the footer where it should be loaded to track visitors? – Brad Dalton Feb 27 '14 at 4:47
  • Did you resolve this successfully? – Andy Macaulay-Brook Aug 5 '16 at 18:21
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

0

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.

0

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!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.