仅为Wordpress中的博客初始化第二个主题

时间:2013-01-20 21:11:34

标签: php wordpress wordpress-theming

我使用wordpress开发了一个博客网站。在我准备好主题之后,网站所有者让我使用他仅为网站博客购买的其他主题。

如何在不将其设置为选项表上的网站主题的情况下初始化第二个主题?

我可以在TEMPLATEPATH

中定义常量wp-includes/default_constants.php
function 'wp_templating_constants':
define('TEMPLATEPATH', get_theme_root() . '/theme-name');

设置过滤器:

主题的functions.php中的

pre_option_templatetemplatepre_option_current_themestylesheet_directory_uristylesheet_directory

但是,当然,我想知道用户是否在博客页面上后动态地进行。有谁知道怎么做?

1 个答案:

答案 0 :(得分:1)

以下是插件的代码,用于将主题设置为类别列表,而不是数据库中定义的主题。

new SetTheme('[THEME_NAME]', array('[CAT_NAME]', [CAT_ID], [CAT_OBJECT]));

class SetTheme {
    private $theme_name = '';
    private $categories = array();

    public function __construct($theme_name, $categories) {
        // define original theme location for any reason
        define('ORIGTEMPLATEPATH', get_template_directory());
        define('ORIGTEMPLATEURI', get_template_directory_uri());

        // init class parameters
        $this->theme_name = $theme_name;

        foreach ($categories as $cat) {
            if (is_string($cat))
                $cat = get_category_by_slug($cat);

            $category = get_category($cat);
            $this->categories[$category->term_id] = $category;
        }

        // apply action to setup the new theme only on action 'setup_theme'
        // because some functions are not yet loaded before this action
        add_action('setup_theme', array($this, 'setup_theme'));
    }

    public function setup_theme() {
        // if the current post or category is listed, apply the new theme to be initialized
        if ($this->is_category_theme())
            $this->set_theme();
    }

    private function is_category_theme() {
        // get category from current permalink
        // and check if is listed to apply the new theme
        $current_cat = get_category_by_path($_SERVER["HTTP_HOST"] . $_SERVER['REQUEST_URI'], false);
        if (isset($this->categories[$current_cat->term_id])) return true;

        // get post from current permalink
        // and check if it belongs to any of listed categories
        $current_post = url_to_postid($_SERVER['REQUEST_URI']);
        $post_categories = wp_get_post_categories($current_post);
        foreach ($post_categories as $cat_id)
            if (isset($this->categories[$cat_id])) return true;

        return false;
    }

    private function set_theme() {
        // apply the filters to return the new theme's name
        add_filter('template', array($this, 'template_name'));
        add_filter('stylesheet', array($this, 'template_name'));
    }

    public function template_name() {
        // return new name
        return $this->theme_name;
    }
}

该类的参数是主题名称和类别数组(ids,slugs或类别对象)。

当然,这是我需要的,可能对于其他主题,它将需要函数'set_theme'中的其他过滤器。

它需要是一个插件,因为插件在主题之前加载,甚至在WP类之前加载。

使用此插件,永远不会调用原始插件(至少在我的情况下)。