Place Ads only on Homepage - WordPress

#1

Hi,

How to place an ad that will be only visible in Homepage and not at any other pages?

@GulshanKumar

TIA

#2

Assuming, you want to place in the Sidebar widget but only for the Homepage; here we go …

  1. Add below code
// Extend shortcode support to widget
add_filter( 'widget_text', 'shortcode_unautop');
add_filter( 'widget_text', 'do_shortcode');

add_shortcode( 'homepage_ad', function() {
    if ( is_front_page() && is_home() ) { // Detect homepage or custom front page
        $adCode = '<!-- Ad unit only for Homepage -->
        <script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
        <!-- AdSense Responsive Ad Code -->
        <ins class="adsbygoogle"
             style="display:block"
             data-ad-client="ca-pub-1234567890"
             data-ad-slot="0987654321"
             data-ad-format="auto"></ins>
        <script>
        (adsbygoogle = window.adsbygoogle || []).push({});
        </script>
        <!-- Ad unit only for Homepage -->';
        return $adCode;
	}
} );
  1. Use the shortcode [homepage_ad] in the sidebar widget.

Please take backup before proceeding. Consider using Code Snippets plugin to safely place these code.

#3

It didn’t work. It is showing the shortcode itself.

#4

May I know, where exactly are you placing the Ad? Share a screenshot.

#5

I want to place the Ad below the header, And I have an option to do the same in my Theme Options.

#6

Does it support PHP code?

#7

Alternatively, I think you can do via CSS.

#8

It has a regular Text window, just like what we get in the Text sidebar widget.

#9

No need to use any PHP code. Forget all what I written above.

Try this easiest method.

  1. Place your ad code
<div class="advt" style="display:none;" >

 <script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
        <!-- AdSense Responsive Ad Code -->
        <ins class="adsbygoogle"
             style="display:block"
             data-ad-client="ca-pub-1234567890"
             data-ad-slot="0987654321"
             data-ad-format="auto"></ins>
        <script>
        (adsbygoogle = window.adsbygoogle || []).push({});
        </script>

</div>
  1. Add this custom CSS code
/* Display ad on Homepage only */
.home .advt{
    display: block !important;
}

That’s all. Let me know if this work for you or not.

#10

Thank you Bro…

It worked

#11

Good to know. :slight_smile:

You’re welcome! :+1:

2 Likes
closed #12

This topic was automatically closed 3 days after the last reply. New replies are no longer allowed.