1

I want to make an specific theme for non logged in users, but I don´t know how to make the function or plugin to shift the theme for them, and left another specific theme for logged in users.

Anyone knows how to do this? The only clues I had are the functions switch_theme and is_user_logged_in, but don´t know how to make them work to do this.

Thanks for your time.

2 Answers 2

4

You can override the theme WordPress uses with the template and stylesheet filters:

/**
 * Override the current theme to show non-logged in users.
 * 
 * @link    http://wordpress.stackexchange.com/q/142418/1685
 * 
 * @param   string  $theme
 * @return  string
 */
function wpse_142418_nopriv_theme( $theme ) {
    if ( ! is_user_logged_in() ) 
        $theme = 'mythemefoldername';
    return $theme;
}

add_filter( 'stylesheet', 'wpse_142418_nopriv_theme' );
add_filter( 'template',   'wpse_142418_nopriv_theme' );
4
  • 1
    As @kaiser mentioned, switch_theme will make relentless updates to the DB. Using these filters will not. Apr 25, 2014 at 13:32
  • And that's why I upvoted you :)
    – kaiser
    Apr 25, 2014 at 13:33
  • Works for child themes and parent themes? Apr 25, 2014 at 15:14
  • 1
    If you just want to override a child theme, use only the stylesheet filter. Apr 25, 2014 at 15:19
4

Functions - under the hood

While is_user_logged_in() can be used to determine the difference between a guest and a logged in (and therefore registered) user, switch_theme( $stylesheet ) alters actual database entries in the {$wpdb->options} table:

update_option( 'template', $template );
update_option( 'stylesheet', $stylesheet );
update_option( 'current_theme', $new_name );
if ( count( $wp_theme_directories ) > 1 ) {
    update_option( 'template_root', get_raw_theme_root( $template, true ) );
    update_option( 'stylesheet_root', get_raw_theme_root( $stylesheet, true ) );
} else {
    delete_option( 'template_root' );
    delete_option( 'stylesheet_root' );
}
update_option( 'theme_switched', $old_theme->get_stylesheet() );

Simple solution: Two stylesheets.

Therefore I wouldn't recommend doing so. Simply switch "themes" - read: loaded stylesheets - on a user/guest basis

$stylesheet  = plugins_dir_url( __FILE__ ).'assets/';
$stylesheet .= is_user_logged_in()
    ? 'style-user.css'
    : 'style-guest.css;
wp_enqueue_style(
    'main-stylesheet',
    $stylesheet
    array( 'commons.css' )
    1.0
);

As you can see, I add a dependency of commons.css to the stylesheet. This would be another, previously registered/enqueued stylesheet that has all definitions that are shared between both.

1
  • 2
    Like your two stylesheets method. +1 Apr 25, 2014 at 13:51

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.