Using WordPress ‘preview_theme()’ PHP function

The preview_theme() WordPress PHP function starts the preview theme output buffer.

Usage

preview_theme();

Parameters

  • None

More information

See WordPress Developer Resources: preview_theme

Examples

Previewing a Theme

This example demonstrates how to enable the preview of a theme when a user has the required permissions and the necessary query variables are present:

// Check if user has the required permissions
if (current_user_can('switch_themes')) {
// Check if 'template' and 'preview' query variables exist
if (isset($_GET['template']) && isset($_GET['preview'])) {
// Start preview theme output buffer
preview_theme();
}
}

Adding a Preview Theme Button

In this example, we’ll create a ‘Preview Theme’ button that will only show when a user has the required permissions to preview a theme:

// Check if user has the required permissions
if (current_user_can('switch_themes')) {
// Create a 'Preview Theme' button with the necessary query variables
echo '<a href="' . esc_url(add_query_arg(array('template' => 'my_new_theme', 'preview' => 1), home_url())) . '" target="_blank">Preview Theme</a>';
}

Customizing the Preview Theme URL

This example shows how to customize the preview theme URL by adding a custom template and preview parameters:

// Set custom template and preview parameters
$template = 'custom_theme';
$preview = 1;

// Create the preview theme URL with the custom parameters
$preview_theme_url = esc_url(add_query_arg(array('template' => $template, 'preview' => $preview), home_url()));

// Output the preview theme URL
echo $preview_theme_url;

Displaying a Message When Previewing a Theme

In this example, we’ll display a message to the user when they are previewing a theme:

// Check if 'template' and 'preview' query variables exist
if (isset($_GET['template']) && isset($_GET['preview'])) {
// Output a message to the user
echo '<p>You are currently previewing the ' . esc_html($_GET['template']) . ' theme.</p>';
}

Redirecting to a Specific Page When Previewing a Theme

This example demonstrates how to redirect users to a specific page when they are previewing a theme:

// Check if 'template' and 'preview' query variables exist
if (isset($_GET['template']) && isset($_GET['preview'])) {
// Redirect to a specific page when previewing the theme
wp_redirect(esc_url(add_query_arg(array('page_id' => 123), home_url())));
exit;
}