Managing Content You See in WordPress Preview Mode [WordPress Tip]
If you are a regular WordPress user who publish posts regularly, the Preview mode needs no introduction. We use it often to preview our posts as we write, or to do a final check before we hit the publish button. But do you know there is actually more that we can do in this mode?
WordPress has a tag called
is_preview which provides flexibility in adding or removing content and codes while the content is viewed under Preview mode. You can display notifications or even hide certain content using simple code snippets like the ones below.
Recommended Reading: 30+ (More) Most Wanted WordPress Tips, Tricks And Hacks
Displaying Notification in Preview Mode
An example of a real-life application for
is_preview tag would be for displaying a notification.
For example: when previewing post, WordPress does not show anything that tells the users that they are in Preview Mode. We can use this tag to display a notification that what is seen is in Preview mode.
is_preview tag, we can write some thing like this in the header.php of the theme.
<?php if(is_preview() ) : ?> <div class="alert alert-info"> <strong>Note:</strong> You are previewing this post. This post has not yet been published. </div> <?php endif; ?>
The code above will show the notification only when we are in preview mode. Add some CSS styles, so that it looks nice, like so.
Hiding Ads/Analytics in Preview Mode
Another case would be for delivering Ads and Analytic codes. If you use AdSense and Google Analytics you can hide them in Preview Mode. This will minimize accidental clicking of your own ads (which is against the Google AdSense TOS), as well as the tracking of your own visit by Google Analytics.
In addition, it will also be useful for ads that count on pageview too, the advertisers will see more accurate pageview count as we hide their ads during the Preview Mode.
To hide ads, you can add the following code.
<?php if(!is_preview()) : ?> // Ads Code <?php endif; ?>
! notation that came before the
is_preview tag that you see above will negate the condition, so it will show the ads only when we are not in Preview Mode.
For Google Analytics, insert the following code in the header.php or footer.php.
<?php if(!is_preview() && !is_admin()) : ?> // Google Analytics Code <?php endif; ?>
Notice that I’ve also added the
is_admin tag. This addition will also remove Google Analytics when we are logged in as Administrator.
We hope that you find these little pieces of code useful and will save these snippets for use, if needed. If you have any question regarding this topic, feel free to ask in the comments area.