How to Remove Ad Codes on 404 Pages in WordPress?

This guide is about Fix AdSense crawler 404 page error and solution to remove ad codes on WordPress 404 pages.

How to remove ad codes on 404 pages?

  1. Open “Appearance > Theme File Editor” page.
  2. Click and open the “Theme Functions” page.
  3. Add following code to functions.php file and Update file.
function conditional_adsense_display() {
if ( ! is_404() ) echo '<script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=YOUR_PUBLISHER_ID_HERE" crossorigin="anonymous"></script>';
}
add_action('wp_head', 'conditional_adsense_display');

Before using the above code, replace “YOUR_PUBLISHER_ID_HERE” text with your publisher ID.

NOTE: after completing the above steps, don’t forget to test normal and 404 pages to confirm that ads display properly on normal pages and not display on 404 pages.

Suggestion: To protect your above changes while theme update, add above code in Child theme functions.php file.

AdSense crawler 404 page error

When you add your AdSense ad code on the WordPress header or footer section, it will load on all pages.

In this case, you can face an AdSense crawler 404 page error in the AdSense dashboard. Because,

If the URL sent to Google points to a page that doesn’t exist (or no longer exists) on a site, or results in a 404 (Not Found) error, the ads crawler won’t successfully crawl your content.

Sometimes this results in AdSense policy violation issues and ads may be restricted on 404 pages.

To solve this problem, you can conditionally remove ad code from 404 pages. You can do this without any WordPress plugin and by following the above given steps.