Page template across themes

时间:2012-07-02 作者:Raymond

是否可以使页面模板可用于多个或所有主题,而不必将页面模板保存在每个主题文件夹中?

可能类似于:themes/globalform.php 而不是针对每个主题执行此操作themes/twentyten/globalform.php

2 个回复
SO网友:brasofilo

我相信你必须为此制作一个插件。以下代码基于此答案:Is it possible to define a template for a custom post type within a plugin independent of the active theme?

/*
Plugin Name: Universal Template
Plugin URI: https://wordpress.stackexchange.com/questions/57211
Description: Uses a custom template in the plugin directory accordding to Conditional Tags (http://codex.wordpress.org/Conditional_Tags), maybe even other conditions
Version: 1.0
Author: brasofilo
Author URI: https://wordpress.stackexchange.com/users/12615
*/

class Universal_Template
{

    public function __construct()
    {       
        $this->url = plugins_url( \'\', __FILE__ );   
        $this->path = plugin_dir_path( __FILE__ );
        add_action( \'init\', array( $this, \'init\' ) );
   }

    public function init() 
    {
        add_filter( \'template_include\', array( $this, \'wpse_57211_my_plugin_templates\' ) );
    }


    public function wpse_57211_my_plugin_templates( $template ) 
    {
        $post_types = array( \'post\' );

        if ( is_post_type_archive( $post_types ) )
            $template = $this->path . \'/single-custom.php\';

        if ( is_singular( $post_types ) )
            $template = $this->path . \'/single-other-custom.php\';

        return $template;
    }

}

$wpse_57211 = new Universal_Template();

SO网友:User

你可以把文件放进去wordpress/wp-content/themes 然后从不同的主题中包含它们。您甚至可以创建一个名为wordpress/wp-content/themes/global-includesshared.

对我来说,包括来自父目录的文件,我不能只做:

<?php include_once "../globalform.php"; ?>

相反,我需要做:

<?php include_once get_template_directory() . "/../globalform.php"; ?>

您也可以使用get_stylesheet_directory() (获取子主题目录)而不是get_template_directory() (如果当前主题是子主题,则将获取父主题目录。因为我们获取的是父目录,所以在这里可能无关紧要。

结束

相关推荐