Hook into theme-switching later than `setup_theme`

I need to add a theme-switching logic to a site. Unfortunately, what I’ve tried already doesn’t seem to work as required.

The themes needs to switch based on whether the user is on the blog part of the site (e.g. is_single(), is_category(), get_post_type() == 'post'), versus any other section (e.g. is_shop(), is_page(), etc.)

Unfortunately, having created a plugin to do this, it appears that none of these conditionals are available at the only point I can feasibly hook in: setup_theme.

With the following:

function vnmFunctionality_getTheme() {

    $isBlog = (is_author() || is_category() || is_tag() || is_date() || is_home() || is_single()) && 'post' == get_post_type();

    if ($isBlog) {
        return 'blog-theme';
    } else {
        return 'site-theme';
    }
}

function vnmFunctionality_conditionalThemeSwitch() {
    if (is_admin()) {
        return;
    }

    add_filter('template', 'vnmFunctionality_getTheme');
    add_filter('stylesheet', 'vnmFunctionality_getTheme');
}

add_action('setup_theme', 'vnmFunctionality_conditionalThemeSwitch', 100);

This works (insofar as there are no errors), but $isBlog will always return false because none of those conditionals are available at setup_theme. If I don’t use add_action('setup_theme') and instead move the add_filter lines to the root of the plugin, the conditionals are available, but it causes a host of other issues (for example, the blog-theme seems to try to act like a messed-up quasi-child of site-theme, and fails to load everything that’s enqueued in site-theme‘s functions file).

I also tried looking at the global $wp_query object to see if I could figure out where you are on the site, but even that seems to be empty at setup_theme.

I can’t seem to hook in any later than setup_theme for the theme-switching to work properly, but that seems too early to be able to figure out where the user actually is on the site. Is there a way of achieving this?

For reference: The need is based on requirements outside of my influence (read: client). This secondary ‘blog-only’ theme is fundamentally different from the rest of the site (and was produced by another developer), so unfortunately integrating it into the existing theme isn’t feasible.

1 Answer
1

Assuming that the blog part of the site has a different url-structure (eg www.example.com/blog/this-is-my-blogpost) you can use the PHP $_SERVER variable to determine which page is being called and use that in an expression to make $isBlog true at the appropriate moment.

Leave a Comment