is_single not working in functions.php wordpress [Solved]

wordpressI’ve been trying to add a condition for is_single() in my WordPress themes functions.php to show ads on blog posts only and not on other pages. However, the condition, if(is_single()){} wasn’t working as expected, i.e, it wasn’t returning positive for single post page too and thus failing again n again.

Upon investigating and playing around, the solution was that the condition has to be used inside a function and not in the functions.php file openly.

Take the following example which I used for my theme code to show adsense on single post page only and not on wordpress is_page() pages.

This is incorrect way of using wordpress conditional hooks (outside functions in functions.php)

if(is_single()) {
add_action('the_content', sharebox);
}

function sharebox($content){
$nabtron_before_content = "stuff to show before content";
$nabtron_after_content = "stuff to show after content";
$content = $nabtron_author_adsense.$content.$nabtron_after_content;
}

This will not work, as the condition for checking if the page is a single post or a wp page is not inside a functions.

This is correct way to use conditional is_single() or any other in functions.php

To use the conditional function correctly inside functions.php, add it inside a function like this and it will work inshaAllah:

add_action('the_content', sharebox);
function sharebox($content){
if(is_single()) {
$nabtron_before_content = "stuff to show before content";
$nabtron_after_content = "stuff to show after content";
$content = $nabtron_author_adsense.$content.$nabtron_after_content;
}
}

Let me know if you have any queries or suggestions related to it!

hire best wordpress php css developer
Need Help? Hire me now!
I can help you in anything related to webdevelopment, including: HTML, CSS, PHP & MySql, WordPress (plugins & themes development, others), regular expressions, server management, etc.

4 comments on “is_single not working in functions.php wordpress [Solved]

Leave a Reply

Your email address will not be published.