鱼见海源码网-免费PHP网站源码模板,插件软件资源分享平台!

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

鱼见海资源网最新教程:

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文件如下。

My custom page

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

文章来源于互联网

© 版权声明
THE END
喜欢就支持一下吧
点赞134 分享
评论 抢沙发
头像
欢迎您留下宝贵的见解!
提交
头像

昵称

取消
昵称表情代码图片

    暂无评论内容