Skip to content

Instantly share code, notes, and snippets.

@soderlind
Last active April 2, 2022 15:50
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save soderlind/b4fccf625338ad9b7baeb494c95d45fa to your computer and use it in GitHub Desktop.
Save soderlind/b4fccf625338ad9b7baeb494c95d45fa to your computer and use it in GitHub Desktop.
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
Copy link
Author

soderlind commented Jan 10, 2017

Added missing template_directory_uri

@soderlind
Copy link
Author

Added missing stylesheet_uri

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment