温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

怎么在WordPress中利用get_header()获取头部函数

发布时间:2021-01-11 15:26:33 来源:亿速云 阅读:195 作者:Leah 栏目:开发技术

怎么在WordPress中利用get_header()获取头部函数?很多新手对此不是很清楚,为了帮助大家解决这个难题,下面小编将为大家详细讲解,有这方面需求的人可以来学习下,希望你能有所收获。

函数意义详解
从当前主题调用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(); ?>
<h3>Error 404 - Not Found</h3>
<?php get_sidebar(); ?>
<?php get_footer(); ?>

2.多种头部

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

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

看完上述内容是否对您有帮助呢?如果还想对相关知识有进一步的了解或阅读更多相关文章,请关注亿速云行业资讯频道,感谢您对亿速云的支持。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI