Using WordPress ‘preview_theme_ob_filter_callback()’ PHP function

The preview_theme_ob_filter_callback() WordPress PHP function manipulates preview theme links in order to control and maintain location.

Usage

preview_theme_ob_filter_callback($matches);

Custom example:

Input:

$matches = array('href="http://example.com"', 'http://example.com');

Output:

href="http://example.com?preview=true"

Parameters

  • $matches (array) – Required. An array containing the matched URL strings.

More information

See WordPress Developer Resources: preview_theme_ob_filter_callback

Examples

The following code adds a ?preview=true query to all theme links, allowing users to preview the theme.

function add_preview_query_to_theme_links($buffer) {
return preg_replace_callback( '|<a([^>]*) (href=[\'"]([^\'"]+)[\'"])|', 'preview_theme_ob_filter_callback', $buffer);
}

ob_start('add_preview_query_to_theme_links');

Previewing a Specific Theme

This code previews the “Twenty Twenty” theme by setting the preview query in the URL.

function preview_twenty_twenty_theme($buffer) {
if ('twentytwenty' === wp_get_theme()->get('TextDomain')) {
return preg_replace_callback( '|<a([^>]*) (href=[\'"]([^\'"]+)[\'"])|', 'preview_theme_ob_filter_callback', $buffer);
}
return $buffer;
}

ob_start('preview_twenty_twenty_theme');

Previewing Themes on a Specific Page

This example previews themes only on the homepage by checking if is_home() is true.

function preview_theme_on_homepage($buffer) {
if (is_home()) {
return preg_replace_callback( '|<a([^>]*) (href=[\'"]([^\'"]+)[\'"])|', 'preview_theme_ob_filter_callback', $buffer);
}
return $buffer;
}

ob_start('preview_theme_on_homepage');

Previewing Themes for Logged-In Users

This code previews themes only for logged-in users by checking if is_user_logged_in() is true.

function preview_theme_for_logged_in_users($buffer) {
if (is_user_logged_in()) {
return preg_replace_callback( '|<a([^>]*) (href=[\'"]([^\'"]+)[\'"])|', 'preview_theme_ob_filter_callback', $buffer);
}
return $buffer;
}

ob_start('preview_theme_for_logged_in_users');

Previewing Themes for Admin Users

This code previews themes only for admin users by checking if the user has the ‘manage_options’ capability.

function preview_theme_for_admin_users($buffer) {
if (current_user_can('manage_options')) {
return preg_replace_callback( '|<a([^>]*) (href=[\'"]([^\'"]+)[\'"])|', 'preview_theme_ob_filter_callback', $buffer);
}
return $buffer;
}

ob_start('preview_theme_for_admin_users');