Search code examples
phpwordpressshortcode

Shortcode EXCLUSIVELY on single.php


I created a shortcode for adsense for my website's posts something like [ads1] which will display google adsense 336x280 ad. I put the [ads1] at the beginning of the post. To now, everything is ok.... but I noticed if I access my home page www.websiteexemple.com (on the home page I have 12 post displayed) then every post will display the ad that I put it at the begining. So how I can display that ad only on the posts (single.php) but not on the website homepage or other pages like archive, categories, tags ... etc?

Ps: I put the shortcode in functions.php

Pss: Until now I used quick adsence - a wordpress plugin that works fine adding ads with shortcode.... but I gave it up. I dont want to use any plugin anymore!!!.

My code:

function adsense1() {
return 'Here come the google ads code provided by adsense';
}
add_shortcode('ads1', 'adsense1');

Solution

  • Try this

    function adsense1() 
    {
        if(is_singular())
        {
            return 'Here come the google ads code provided by adsense';
        }
    }
    add_shortcode('ads1', 'adsense1');
    

    Additionally, you can pass post-type as a is_singular param like this is_singular('post').