plugin development – Getting Post ID at “stylesheet” and “template” hooks

Question

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.

0
HHGK 8 months 2021-12-06T12:59:25-05:00 0 Answers 0 views 0

Leave an answer

Browse
Browse