0

I'm trying to create a plugin where you can select a different theme on every page.

To get the selected theme I need to get the post id inside the "stylesheet" and "template" hooks at the point where Wordpress selects the theme:

add_filter( 'stylesheet','hk_get_theme');
add_filter( 'template','hk_get_parent_theme' );

function hk_get_theme($stylesheet){
  $postID = $GLOBALS['post']->ID;
  if ($postID != false) {
    $selectedTheme = get_post_meta( $postID, 'hk_theme_select', true );
    if (isset($selectedTheme) && $selectedTheme != '') {
       $theme = $selectedTheme;
    }
  }
  $theme = $theme ? esc_attr( $theme ) : $stylesheet;
  return $theme;
}

function hk_get_parent_theme( $template ){
  $postID = $GLOBALS['post']->ID;
  if ($postID != false) {
    $selectedTheme = get_post_meta( $postID, 'hk_theme_select', true );
    if (isset($selectedTheme) && $selectedTheme != '') {
       $child_theme = $selectedTheme;
    }
  }
  $themes = wp_get_themes();
  if( !isset( $themes[$child_theme] ) ) {
    return $child_theme;
  }
  $theme = $themes[$child_theme];
  if( isset( $theme->template ) ){
    return $theme->template;
  }
  return $template;
}

Unfortunately the first times the "stylesheet" and "template" hooks are executed the post id doesn't seem to be there.

Is there any other way to get the page meta data that early? Or an other way to store the selected theme for a page to get this data at this early point? Please no cookie.

1
  • I'm loading the filters via: add_action( 'plugins_loaded','hk_replace_theme',99 ); function hk_replace_theme(){ add_filter( 'stylesheet','hk_get_theme'); add_filter( 'template','hk_get_parent_theme' ); }
    – HHGK
    Dec 6, 2021 at 18:19

1 Answer 1

0

This is not possible via those hooks. It's too early.

The reason it isn't possible is because theme loading happens very early. There is no post to fetch yet, WordPress hasn't processed the URL or created the main query. It's so early that post types haven't been defined yet. Even the init hook hasn't happened.

2
  • also, if you specified a theme for a CPT that does not register that CPT it would generate a 404 error. Likewise none of the theme mods would match up so nav menus etc would all revert to their default. The only way I can see to do this is to note down the full URL then switch the theme based on the URL and hope the post and everything it needs is present in the other theme. This won't scale past a small number of posts though
    – Tom J Nowell
    Dec 6, 2021 at 19:47
  • Also, it's somewhat obsolete when considering that in block based themes any page can have its own completely unique template and block styling
    – Tom J Nowell
    Dec 6, 2021 at 19:48

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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