I have a custom tracking system in place which works with an include of a .js file in the footer of each page. Unfortunately some high traffic sites are including images from my site which are already removed. therefor the 404 error page of my theme is frequenty hit and those users are registered aswell as website visitors even though I dont want them to count.

Long story short: I want to provent that tracking.js file to load on the 404 error page. What would be the best way to do that?

  • How are you adding the JS file to the site? With wp_enqueue_script()? Jun 9 '19 at 4:21

There is is_404(). I normally use it to do just the opposite, to add CSS and JS animations which are specific to the 404 error page. In your case that would be:

function wpse_339946() {

    if ( ! is_404() ) {
        wp_enqueue_script( 'tracking-js', get_template_directory_uri() . '/js/tracking.js' );

add_action( 'wp_enqueue_scripts', 'wpse_339946' );

You could use the is_page() function on your footer to check if it is a 404 page, then don't add the js code if it is the 404 page. Added the commenter is right - a 404 is a response, not a page, so you can't test for it. (I blame temporary insanity...) So .... the answer is now....

updated Create a 404 page template that doesn't include the js code. That template will be used is a page request causes a '404' response.

Related to your question: I also worry about incomplete tracking because of ad blockers. So developed a server-side tracker that sends GA tracking data. Ad-blockers never see it, so I get full tracking data. (With GDPR notifications, of course.) Perhaps an alternative for you.

  • The 404 page is not a "page", so is_page() couldn't be used. Jun 9 '19 at 4:21

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.