Using WordPress ‘is_preview()’ PHP function

The is_preview() WordPress PHP function determines whether the query is for a post or page preview.

Usage

if (is_preview()) {
    // Do something if it's a preview
}

Parameters

  • None

More information

See WordPress Developer Resources: is_preview()

Important: is_preview() does NOT check if the user is logged in or if the user can even edit the post. Use current_user_can() for checking roles and capabilities. Any visitor can add ?preview=true, ?preview=1, or ?preview=not_false to the URL, and is_preview() will return true.

Examples

Prevent analytics code from loading on preview pages

If you don’t want to load your analytics code on preview pages, use the is_preview() function:

if (!is_preview()) {
    // Include analytics code
}

Show a message on preview pages

Display a message to users when they are previewing a post or a page:

if (is_preview()) {
    echo 'This is a preview. Your changes have not been published yet.';
}

Disable comments on preview pages

If you want to disable comments on preview pages, you can use is_preview() in your comments section:

if (!is_preview()) {
    comments_template();
}

Customize content for preview pages

Modify the content displayed when users are previewing a post or a page:

$content = get_the_content();

if (is_preview()) {
    $content .= '<p><em>This is a preview. Your changes have not been published yet.</em></p>';
}

echo $content;

Hide sidebar on preview pages

Hide the sidebar when users are previewing a post or a page:

if (!is_preview()) {
    get_sidebar();
}