详解WordPress开发中get_header()获取头部函数的用法

yipeiwu_com6年前PHP代码库

函数意义详解
从当前主题调用header.php文件。是不是很简单?好吧,如果你是新手的话这里要提醒一下,这里的get和get_children()、get_category中的get略有不同之处。

get_header函数声明(定义)
之前写文章很少会写到函数定义的代码,后来自己翻看的时候发现这个习惯不太好,所以决定,只要篇幅允许,就会把函数主题贴出来,方便自己翻看。
get_header 函数,声明(定义)的位置,是在 wp=include/general-template.php 文件的第 24 – 36 行左右的位置。

function get_header( $name = null ) {
 do_action( 'get_header', $name );
 
 $templates = array();
 if ( isset($name) )
 $templates[] = "header-{$name}.php";
 
 $templates[] = 'header.php';
 
 // Backward compat code will be removed in a future release
 if ('' == locate_template($templates, true))
 load_template( ABSPATH . WPINC . '/theme-compat/header.php');
}

get_header函数的使用

<?php get_header( $name ); ?>

很简单,从上面的函数声明中我们也能看出,该函数只接受一个变量作为参数。

参数解释
$name ,从上面的函数声明中我们可以看出,$name是一个字符串型变量,用来调用header的别名模板,
比如 $name = “ab”;
也就是我们这样

<?php 
  $name = “ab”
  get_header( $name ); 
 
?>

这将会调用 header-ab.php 文件作为头部文件的调用。

例子:

1.简单的 404 页面

下面的代码是一个简单模板文件,专门用来显示 "HTTP 404: Not Found" 错误的 (这个文件应该包含在你的主题中,名为 404.php)

<?php get_header(); ?>
<h2>Error 404 - Not Found</h2>
<?php get_sidebar(); ?>
<?php get_footer(); ?>

2.多种头部

为不同的页面显示不同的头部

<?php
if ( is_home() ) :
 get_header( 'home' );
elseif ( is_404() ) :
 get_header( '404' );
else :
 get_header();
endif;
?>

这些为 home 和 404 准备的头部应该分别命名为  header-home.php 和 header-404.php 。

相关文章

PHP Undefined index报错的修复方法

虽然可以通过设置错误显示方式来隐藏这个提示,但是这样也有隐患,就是在服务器的日志中会记录这些提示,导致日志文件异常庞大。 首先,这个不是错误,是warning。所以如果服务器不能改,每个...

PHP URL地址获取函数代码(端口等) 推荐

php 获得当前的脚本网址(只有路径) 复制代码 代码如下: function GetCurUrl() { if(!empty($_SERVER["REQUEST_URI"])) { $...

WordPress中"无法将上传的文件移动至"错误的解决方法

今天在网页上传图片到博客,结果提示:“无法将上传的文件移动至 /home/wwwroot/wp-content/uploads/2013/”,郁闷了,认为是权限问题,修改了文件,都改成了...

解析php中获取系统信息的方法

$root = getenv('DOCUMENT_ROOT'); ////服务器文档根目录$port = getenv('SERVER_PORT'); ////服务器端口$file =...

php代码收集表单内容并写入文件的代码

至于表单内容,这里就不多说了,主要是表单的action="getpost.php",也就是写getpost.php这个文件。下面就把这个文件里面的内容贴出来。 复制代码 代码如下: &l...