Activating a WordPress Child Theme in Code

I ran into this problem while building a mobile version of a WordPress theme. To support a mobile version, I decided to make a child theme that had bare-bones CSS and other mobile goodies. I wanted this child theme to be active when requests came in from known mobile and handheld devices.

Using the filters ‘template‘ and ‘stylesheet‘ in my parent theme’s functions.php , I was able to override the default theme and use my child theme instead.

I hit a snag though, when using get_template_part(). It was ALWAYS deferring to my parent theme for files!

The problem was that setting up filters in a theme’s functions.php is TOO LATE. Constants are already defined that determine the parent and child locations for templates and stylesheets.

You need to write a plugin, and put the same filters and override functions in THERE. To keep it clean, I used the ‘setup_theme‘ action, then added my override filters:

add_action( 'setup_theme', 'my_setup_theme_action', -1 /* early */ );

function my_setup_theme_action() {
    add_filter( 'template', 'my_template_filter' );
    add_filter( 'stylesheet', 'my_stylesheet_filter' );

Bingo. 🙂

Leave a Reply