Leave a Reply

2 comments

  1. There are several issues with your code. Let’s start at the beginning…

    Adding hooks

    All your hooks will be added at the backend. Even those which are outside the if((is_admin)) branch. Add your hooks explicitly where they should work:

    if (is_admin()){
      // do this on backend (admin side)
        /* load plugin functions */
        add_action('add_meta_boxes', 'myplugin_add_meta_box');
        add_action('save_post', 'myplugin_save_meta_box');
    
    } else {
      // if we are NOT on backend (admin side) we have to be on frontend, because there is only frontend and backend.
        /* load page theme */
        add_filter( 'option_template', 'my_plugin_get_page_theme');
        add_filter( 'template', 'my_plugin_get_page_theme');
        add_filter( 'option_stylesheet', 'my_plugin_get_page_theme');
    
    }
    

    In the loop or not?

    get_the_ID() must be within the loop. Where are your hooks (‘option_template’, ‘template’ and ‘option_stylesheet’) are done? Before the query is done or after (means: inside the loop or outside) ?
    Two lines of code give us the answer:

    global $post;
    var_dump( $post );
    

    If $post is empty (null), we are outside the loop. We hooked to early. We need a hook after the query is done. The ´init´ hook is an odd one. Let’s alter the code above a bit and get the plugin working:

    if (is_admin()){
    
        /* load plugin functions */
        add_action('add_meta_boxes', 'myplugin_add_meta_box');
        add_action('save_post', 'myplugin_save_meta_box');
    
    } else {
    
        add_action( 'init', 'my_template_hooks', 5, 0 );
    
    }
    
        function my_template_hooks(){
    
            /* load page theme */
            add_filter( 'option_template', 'my_plugin_get_page_theme');
            add_filter( 'template', 'my_plugin_get_page_theme');
            add_filter( 'option_stylesheet', 'my_plugin_get_page_theme');
    
        }
    

    Now our hooks are inside the loop and the plugin works fine.

    Deprecated function

    On line 28 of your plugin code you use $themes = get_themes();. get_themes() is deprecated and should be replaced with ´wp_get_themes()´.

    Development

    Please enable WP-debugging (set WP_DEBUG to TRUE in your wp-config.php). The debug messages will help you much.

    You can find the complete modified code on Github

  2. As far I know, to use post->ID outside of loop, wp_query should be called first. I mean something like that the code bellow which is already suggested by @Jan

    global $wp_query; 
    $postid = $wp_query->post->ID;
    

    Optionally, get_post_id() can work for you, check codex for more.