Add JS to on Specific Pages via functions.php in WordPress [Example: For Adsense]

I started to write English blog posts with some technical information in order to remember myself and to help people on my personal blog that I have not used for a long time. As a result, the visits increased and I decided to add Adsense ads only to the pages with text, except for pages such as homepage and contact, so no unnecessary slow down on unrelated pages. To do this, the first thing that came to my mind was that I could add JS with an if statement in functions.php.

In this example i inserted this JS on only singular posts and publications page. You can get your page/post id via clicking edit or written in the classes of the page in view-source. Customize the if as your desire.

// call the function that adds your current script
function customjs_load()
{
//if (is_page(23578))
if (is_singular('post') || (is_page(23578)) )
{
?>
<script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-XXXXXXXXXXXX"
crossorigin="anonymous"></script>
<?php
}
}
add_action('wp_head', 'customjs_load', 2);

https://stackoverflow.com/questions/53352262/add-js-to-head-of-specific-page-via-functions-php-in-wordpress

https://stackoverflow.com/questions/4290420/wordpress-how-to-check-whether-it-is-post-or-page

Related Posts