Fully automated theme install and activation via a plugin

I’ve managed to get my “semi noob proof” site installer plugin 98% complete, but I’m having a slight issue with the theme activation. The plugin is able to copy the theme into the themes directory fine. However, my switch_theme statement that attempts to set it to the active theme is missing something.

I’m using…

Read More
function activate_theme(){
switch_theme('my_theme', 'style.css');
}

…as a trigger statement inside the plugin to activate the newly uploaded theme (its uploaded as part of a function that processes further up in the code from the “activate_theme()” function. My theme, in this instance is called ‘my_theme’ and that’s what I’m using in the theme’s style.css

I can tell that the switch theme is partially working, since when I click on “Appearance”, the default 2010 theme is no longer the active theme, however, the “my_theme” theme is not set to active either. Its as if the process only partially completed and neither 2010 nor my theme are fully activated. So, I still have to manually click “Activate” to finish the process.

What could I be missing?

Related posts

Leave a Reply

2 comments

  1. I think, you must also set the options template and stylesheet, thats all.
    I use this via filter to set a theme for testing or on a category, post-type and so on. But you must change the fields in table options for active the theme ready.

    I hope this help, i dont tested – only my idea.

  2. Yes it is. Here is my function:
    https://wordpress.stackexchange.com/a/302650/29133

    /*
     * For directory structure like:
     * 
     * /your-plugin/
     * - /your-plugin.php
     * - /themes/
     * - - /yourthemename/
     *
     * 
     */
    

    Add to the your-plugin.php file:

    function updateTheme($theme){
        update_option('template', $theme);
        update_option('stylesheet', $theme);
        update_option('current_theme', $theme);
    }
    
    add_action( 'setup_theme', 'change_theme' );
    
    function change_theme(){
    
     //Replace with your own conditional
     $enable_theme = true; // Forcing true;
    
    
      if($enable_theme == true):
    
        register_theme_directory( plugin_dir_path( __FILE__ ) . 'themes' );
        $theme = "yourthemename";
    
      else:
    
        $theme = "default";
    
      endif;
    
        updateTheme($theme);
    }