首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用自定义模板使用函数动态重写page.php或single.php

问使用自定义模板使用函数动态重写page.php或single.php
EN

WordPress Development用户
提问于 2018-03-06 04:14:32
回答 1查看 1.1K关注 0票数 1

我想在插件中添加新的自定义模板(定制-page.php,定制-single.php)。当激活时,我想动态地使用插件的自定义模板来覆盖主题的模板(page.php,single.php)。

有什么函数可以做到这一点吗?

EN

回答 1

WordPress Development用户

回答已采纳

发布于 2018-03-06 05:41:13

可以这样做的一种方法是向钩子{$type}_template添加一个过滤器。

样本代码:

代码语言:javascript
复制
function my_plugin_custom_template( $template, $type ) {
    switch ( $type ) {
        case 'page':
            $template = '/path/to/custom-page-template';
            break;

        case 'single':
            $template = '/path/to/custom-single-template';
            break;
    }
    return $template;
}
add_filter( 'page_template', 'my_plugin_custom_template', 10, 2 );   // Filter for page.php
add_filter( 'single_template', 'my_plugin_custom_template', 10, 2 ); // Filter for single.php

或者,也可以向钩子template_include添加一个筛选器。

样本代码:

代码语言:javascript
复制
function my_plugin_custom_template2( $template ) {
    if ( is_page() ) {
        $template = '/path/to/custom-page-template';
    }
    elseif ( is_single() ) {
        $template = '/path/to/custom-single-template';
    }
    return $template;
}
add_filter( 'template_include', 'my_plugin_custom_template2' );

应该由您来决定筛选哪个钩子;但是,template_include过滤器是在{$type}_template钩子之后调用的。如果查看my_plugin_custom_template()代码,基本上不需要检查当前页面(即查询对象)是否是Page、Post等。

希望这能帮上忙。

票数 4
EN
页面原文内容由WordPress Development提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://wordpress.stackexchange.com/questions/295896

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档