WordPress 多种方法自动加载页面模板

1、在下面的代码中,is_page('custom-page')检查当前页面是否是自定义页面,如果是,则加载插件目录下的templates/template-custom.php文件。

注意:is_page()函数的参数应该是自定义页面的slug或ID。

add_filter( 'page_template', 'custom_template' );
function custom_template( $template ) {
    if ( is_page( 'custom-page' ) ) {
        $template = plugin_dir_path( __FILE__ ) . 'templates/template-custom.php';
    }
    return $template;
}

2、WordPress插件可以使用 theme_page_templates 钩子来自动加载页面模板。

  • 在插件目录中创建一个名为`templates`的文件夹,并在其中创建一个名为`custom-template.php`的模板文件。
  • 在插件主文件中添加以下代码:
function custom_template_init() {
    add_filter( 'theme_page_templates', 'custom_template' );
}

function custom_template( $templates ) {
    $templates['custom-template.php'] = 'Custom Template';
    return $templates;
}

add_action( 'plugins_loaded', 'custom_template_init' );

这个代码段将注册一个名为“Custom Template”的页面模板,并将其链接到`custom-template.php`模板文件。

  • 在插件中使用以下代码来加载页面模板:
function load_custom_template( $template ) {
    global $post;

    if ( ! $post ) {
        return $template;
    }

    if ( 'custom-template.php' == get_post_meta( $post->ID, '_wp_page_template', true ) ) {
        $template = plugin_dir_path( __FILE__ ) . 'templates/custom-template.php';
    }

    return $template;
}

add_filter( 'template_include', 'load_custom_template' );

这个代码段将检查当前页面是否使用了“Custom Template”页面模板,如果是,则加载插件目录中的`custom-template.php`模板文件。 现在,当使用“Custom Template”页面模板时,插件将自动加载`custom-template.php`模板文件。

举报

上一篇

WordPress 判断文章是否存在多种方式

下一篇

WordPress 22个常用消毒安全函数分别举例使用,和组合使用,和使用场景
相关推荐
WordPress类:如何使用WP_REST_Response类的方法set_headers设置响应头
WordPress 多种方法自动加载页面模板
wordpress实现不同分类设置不同的每页显示文章数量
WordPress Rest API发布文章并设置postmeta字段信息
WordPress 自定义文章类型终极教程
WordPress 发布文章百度收录自动提交代码
评论(5)
游客的头像
表情
全部评论 只看作者
最新热门
  1. asukatea的头像 用户头像徽章

    哔哩_脱单doge

    0 回复
  2. 苏源的头像 用户头像徽章

    哔哩_藏狐

    2 回复
    作者觉得很赞