Last active
April 2, 2022 15:50
-
-
Save soderlind/b4fccf625338ad9b7baeb494c95d45fa to your computer and use it in GitHub Desktop.
Change WordPress theme root to a folder in your plugin (src/assets)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Sample use: | |
* WordPres Customizer is dependant on functionality in the theme. Just in case | |
* the current theme doesn't support WordPress Customizer we'll use a theme | |
* that supports it. | |
*/ | |
class NN { | |
private $theme_name = 'twentysixteen'; | |
private $plugin_root; | |
private $plugin_url; | |
public function init() { | |
$this->plugin_root = plugin_dir_path( __FILE__ ); | |
$this->plugin_url = plugins_url( '', dirname( __FILE__ ) ); // note: '' appends a slash to the url | |
add_action( 'setup_theme', function() { | |
add_filter( 'theme_root', array( $this, 'switch_theme_root_path' ) ); | |
add_filter( 'template_directory_uri', array( $this, 'switch_template_directory_uri' ) ); | |
add_filter( 'stylesheet_uri', array( $this, 'switch_template_directory_uri' ) ); | |
add_filter( 'pre_option_stylesheet', function(){ | |
return $this->theme_name; | |
} ); | |
add_filter( 'pre_option_template', function(){ | |
return $this->theme_name; | |
} ); | |
} ); | |
} | |
public function switch_theme_root_path( $org_theme_root ) { | |
$current_theme = wp_get_theme( $this->theme_name ); | |
// if theme exists, no point in changing theme root. | |
if ( $current_theme->exists() ) { | |
return $org_theme_root; | |
} | |
$new_theme_root = $this->plugin_root . 'src/assets'; | |
# Too early to use register_theme_directory() | |
if ( ! in_array( $new_theme_root, $GLOBALS['wp_theme_directories'] ) ) { | |
$GLOBALS['wp_theme_directories'][] = $new_theme_root; | |
} | |
return $new_theme_root; | |
} | |
public function switch_template_directory_uri( $template_dir_uri ) { | |
$new_theme_root_uri = $this->plugin_url . 'src/assets/' . $this->theme_name; | |
return $new_theme_root_uri; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Found a "small" bug, switching theme root worked fine, but in customizer I couldn't save my changes (got "Cheatin' uh?"). Fixed it by applying the filters during setup_theme.