I have a child theme with function.php where I am running a script in the header but now I want to tweak it to run only on posts listed under one category and avoid on homepage or other categories. Here is my existing code which I modified but it is firing the script on the entire website.
add_action('wp_head', 'mailchimp_wp_head');
function mailchimp_wp_head() {
?>
<?php if ( is_category( 93 ) ) :?>
<script id="mcjs">!function(c,h,i,m,p){m=c.createElement(h),p=c.getElementsByTagName(h)[0],m.async=1,m.src=i,p.parentNode.insertBefore(m,p)}(document,"script",".js");</script>
<?php endif; ?>
<?php
}
Thanks!
I have a child theme with function.php where I am running a script in the header but now I want to tweak it to run only on posts listed under one category and avoid on homepage or other categories. Here is my existing code which I modified but it is firing the script on the entire website.
add_action('wp_head', 'mailchimp_wp_head');
function mailchimp_wp_head() {
?>
<?php if ( is_category( 93 ) ) :?>
<script id="mcjs">!function(c,h,i,m,p){m=c.createElement(h),p=c.getElementsByTagName(h)[0],m.async=1,m.src=i,p.parentNode.insertBefore(m,p)}(document,"script","https://chimpstatic/mcjs-connected/js/users/hidden.js");</script>
<?php endif; ?>
<?php
}
Thanks!
Share Improve this question asked Jan 13, 2021 at 15:12 howtocodehowtocode 32 bronze badges 11 | Show 6 more comments1 Answer
Reset to default 2run only on posts listed under one category
I highlighted that "posts" because if so, then the conditional tag you should use is in_category()
and not is_category()
which is for category archive pages (e.g. example/category/foo
) — so for example, is_category( 93 )
checks if the current archive page is for the category (with the ID of) 93, whereas in_category( 93 )
checks if the current post is in the category 93.
So try with:
<?php if ( is_single() && in_category( 93 ) ) :?>
<script id="mcjs">!function(c,h,i,m,p){m=c.createElement(h),p=c.getElementsByTagName(h)[0],m.async=1,m.src=i,p.parentNode.insertBefore(m,p)}(document,"script","https://chimpstatic/mcjs-connected/js/users/hidden.js");</script>
<?php endif; ?>
93
? There could also be plugin or other code which is adding the script on your site, so try deactivating plugins. – Sally CJ Commented Jan 13, 2021 at 15:22