AdSense WordPress Shortcode: In this guide, I will show you how to create a WordPress shortcode that allows you to insert Google AdSense ads directly into posts or pages while writing content in WordPress.
Using a shortcode gives you precise control over ad placement without hardcoding ads into templates. This approach works with modern, responsive AdSense code and is compatible with current versions of WordPress.
How to Add an AdSense Shortcode in WordPress
This method adds a small PHP function to your theme that registers a shortcode called [adsense]. When placed inside post or page content, it outputs your AdSense ad unit.
Step 1: Open functions.php
- Log in to your WordPress Admin Dashboard.
- Navigate to Appearance > Theme File Editor.
- Select functions.php from the Theme Files list.
Step 2: Add the AdSense Shortcode Code
Paste the following code near the bottom of your functions.php file. Replace the AdSense values with your own publisher ID and ad slot ID.
<?php
function adsense_shortcode() {
ob_start();
?>
<!-- Google AdSense -->
<ins class="adsbygoogle"
style="display:block"
data-ad-client="ca-pub-0000000000000000"
data-ad-slot="0000000000"
data-ad-format="auto"
data-full-width-responsive="true"></ins>
<script>
(adsbygoogle = window.adsbygoogle || []).push({});
</script>
<?php
return ob_get_clean();
}
add_shortcode('adsense', 'adsense_shortcode');
?>
Step 3: Save Your Changes
Click the Update File button to save the changes.
Step 4: Insert the AdSense Shortcode
When editing a post or page in the WordPress Classic Editor (Text mode), insert the following where you want the ad to appear:
[adsense]
Why Use an AdSense Shortcode?
- Precise control over ad placement
- No need to edit theme templates repeatedly
- Works with responsive AdSense units
- Easier content layout management
- Cleaner and more maintainable theme files
Important Notes
- Follow Google AdSense placement policies carefully
- Do not place ads too close to navigation or clickable elements
- Load the main AdSense script only once per page
- Use a child theme to prevent updates from overwriting your changes
Final Thoughts
Using a WordPress shortcode for Google AdSense remains one of the simplest and most flexible ways to manage ad placement. Once set up, you can easily control where ads appear without touching your theme files again.