使用template_redirect为wordpress添加自定义页面

发表时间:2014-12-22 10:58 | 分类:建站经验 | 浏览:3,810 次

wordpress添加自定义页面一般有两种方法,一种是使用自定义模板,另外一种是使用template redirect 钩子。第一种方法网上教程很多,大致思路是先制作一个自定义的模板,可以从page.php中复制,然后按需求修改,最后创建一个页面,选择这个模板。不清楚的可以网上搜索下,博主这里主要介绍第二种方法。

template_redirect 动作钩子很有用,因为它是 WordPress 知道用户正在浏览的页面的关键。它在特定的页面选择 theme template 之前执行。在只在网站的前端触发,并不在管理员页面触发。

当你需要为特定的页面加载代码的时候,这个钩子很有用。

比如我们要把 example.com/some-custom-url-request 转交给主题文件夹下的 /custom/some-custom-url-request.php 来处理,就可以用这种方式来处理。这种方法相比第一种来说更加的自由,可定制度更高。

在当前主题目录下的模板函数中添加如下代码,即在functions.php最后添加。

function loadCustomTemplate($template) {
    global $wp_query;
    if(!file_exists($template))return;
    $wp_query->is_page = true;
    $wp_query->is_single = false;
    $wp_query->is_home = false;
    $wp_query->comments = false;
    // if we have a 404 status
    if ($wp_query->is_404) {
    // set status of 404 to false
        unset($wp_query->query["error"]);
        $wp_query->query_vars["error"]="";
        $wp_query->is_404=false;
    }
    // change the header to 200 OK
    header("HTTP/1.1 200 OK");
    //load our template
    include($template);
    exit;
}
 
function templateRedirect() {
    $basename = basename($_SERVER['REQUEST_URI'], '?' . $_SERVER['QUERY_STRING']);
    loadCustomTemplate(TEMPLATEPATH.'/custom/'."/$basename.php");
}
  
add_action('template_redirect', 'templateRedirect');

添加这个代码实现了 WordPress 查找当前主题目录 /custom 文件夹下的 php 文件,并且将相匹配的 URL 请求转交给对应的 php 文件来处理的效果。同时这个 php 文件还保持了对 WordPress API 的调用。

在当前主题目录 /custom 文件夹下创建新hello.php文件如下。

<?php get_header();?>
<div id="main">
    <div id="content">
        <div id="post-999" class="page type-page status-publish hentry">
            <h2 class="post-title">My custom page</h2>
            <div class="post-content">
                <?php echo "Hello World"; ?>
                <div class="clear"></div>
            </div><!-- END .post-content -->
            <div class="clear"></div>
        </div><!-- #post-## -->
    </div><!-- END #content -->
    <?php get_sidebar(); ?>
    <div class="clear"></div>
</div><!-- END #main -->
<?php get_footer(); ?>

这是一个简单的示例页面,打开example.com/hello即可显示Hello World,而且也保留了当前主题的页面效果。

演示页面:http://www.bbkzd.com/wenda

参考链接:http://air20.com/archives/409.html

本文标签:

本文链接:https://www.sijitao.net/1856.html

欢迎您在本博客中留下评论,如需转载原创文章请注明出处,谢谢!

一键脚本 博客历程 留言联系 文章归档 网站地图 谷歌地图
Copyright © 2010-2024 章郎虫博客 All Rights Reserved.