Wordpress theme previews

Wordpress theme previews

I'm currently working on a few Wordpress sites, and needed a way for the client to preview my new theme without changing it over for everyone.

<?php

/**
 * Switch theme for specific user while developing
 * Add this code to your functions.php file
 */

function switch_theme_for_developer() {
    // Replace these values with your specific details
    $developer_user_id = 4; // Change this to your user ID
    $development_theme = 'new-theme'; // Change this to your theme's directory name
    
    // Check if user is logged in and matches developer ID
    if (is_user_logged_in() && get_current_user_id() === $developer_user_id) {
        // Switch theme for this specific user
        add_filter('stylesheet', function() use ($development_theme) {
            return $development_theme;
        });
        add_filter('template', function() use ($development_theme) {
            return $development_theme;
        });
    }
}
add_action('init', 'switch_theme_for_developer');

// Optional: Add admin notice to remind you're viewing development theme
function dev_theme_admin_notice() {
    if (is_user_logged_in() && get_current_user_id() === 4) {
        echo '<div class="notice notice-warning is-dismissible">
            <p>You are currently viewing the development theme. Other users see the default theme.</p>
        </div>';
    }
}
add_action('admin_notices', 'dev_theme_admin_notice');