Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Change WordPress theme root to a folder in your plugin (src/assets)
<?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;
}
}
@soderlind

This comment has been minimized.

Copy link
Owner Author

soderlind commented Jan 7, 2017

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.

@soderlind

This comment has been minimized.

Copy link
Owner Author

soderlind commented Jan 10, 2017

Added missing template_directory_uri

@soderlind

This comment has been minimized.

Copy link
Owner Author

soderlind commented Jan 11, 2017

Added missing stylesheet_uri

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.