THE WORDPRESS THEME HEADER TEMPLATE

Now we get into the nitty-gritty: building up your header.php and validating your theme with an HTML Doctype. There’ll be a lot of PHP in this lesson, but don’t despair. We’re also going to do two essential (and kinda neat) search engine optimization techniques and add some more things to your functions.php file.

This lesson assumes that you have already added the basic HTML structural elements to your header.php file, which we covered inWordPress Theme Template and Directory Structure. If yourheader.php file is empty, please work through that lesson first, and then come right back.

The Head Section

Right now your very blank WordPress Theme is technically invalid. That’s because it’s missing a Doctype telling the browser how to interpret the HTML it’s seeing. We’re going to use the HTML5 Doctype. HTML5 has seen enough adoption that now is a great time to use it in a WordPress Theme.

Open up header.php and paste the following code there, before anything else.

01
02
03
04
05
06
07
08
09
10
<?php
/**
 * The Header for our theme.
 *
 * Displays all of the <head> section and everything up till <div id="main">
 *
 * @package Shape
 * @since Shape 2.0
 */
?><!DOCTYPE html>

We’re going to add an opening HTML tag with some attributes that will make the type of page we’re creating more apparent to the browser. At the same time, if the current browser is Internet Explorer 8, the opening HTML tag will have an ID of “ie8″. This allows us to create targeted CSS styles later on, just for IE 8, without having to create a separate stylesheet. Go ahead and add the following, below the Doctype.

1
2
3
4
5
6
<!--[if IE 8]>
<html id="ie8" <?php language_attributes(); ?>>
<![endif]-->
<!--[if !(IE 8) ]><!-->
<html <?php language_attributes(); ?>>
<!--<![endif]-->

The opening HTML tag is wrapped in HTML conditional comments. If the browser is IE8, the HTML tag gets the “ie8″ ID. If the browser is not IE8, don’t include the “ie8″ ID. Want to target more IE versions? Just add more conditional comments.

Now we’re going to get into the get into the <head> section of your WordPress Theme. The <head> section contains meta-information about a web page. Typically stuff like the document title seen at the top of your browser (and in search engine results), and links to stylesheets and RSS feeds. Place the following code below the last code you added.

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
<head>
<meta charset="<?php bloginfo( 'charset' ); ?>" />
<meta name="viewport" content="width=device-width" />
<title><?php
/*
* Print the <title> tag based on what is being viewed.
*/
global $page, $paged;
 
wp_title( '|', true, 'right' );
 
// Add the blog name.
bloginfo( 'name' );
 
// Add the blog description for the home/front page.
$site_description = get_bloginfo( 'description', 'display' );
if ( $site_description && ( is_home() || is_front_page() ) )
echo " | $site_description";
 
// Add a page number if necessary:
if ( $paged >= 2 || $page >= 2 )
echo ' | ' . sprintf( __( 'Page %s', 'shape' ), max( $paged, $page ) );
 
?></title>
<link rel="profile" href="http://gmpg.org/xfn/11" />
<link rel="pingback" href="<?php bloginfo( 'pingback_url' ); ?>" />
<!--[if lt IE 9]>
<script src="<?php echo get_template_directory_uri(); ?>/js/html5.js" type="text/javascript"></script>
<![endif]-->
<?php wp_head(); ?>
</head>
 
<body <?php body_class(); ?>>

If all this looks like gobbledygook to you that’s OK. I’ll explain the main sections.

1
2
<meta charset="<?php bloginfo( 'charset' ); ?>" />
<meta name="viewport" content="width=device-width" />

This is meta information about our content. The first line displays the character set your blog is using. The second line sets the width of the viewport to the width of the device you’re using (for example, a desktop computer, iPhone, iPad, etc).

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
<title><?php
/*
* Print the <title> tag based on what is being viewed.
*/
global $page, $paged;
 
wp_title( '|', true, 'right' );
 
// Add the blog name.
bloginfo( 'name' );
 
// Add the blog description for the home/front page.
$site_description = get_bloginfo( 'description', 'display' );
if ( $site_description && ( is_home() || is_front_page() ) )
echo " | $site_description";
 
// Add a page number if necessary:
if ( $paged >= 2 || $page >= 2 )
echo ' | ' . sprintf( __( 'Page %s', 'shape' ), max( $paged, $page ) );
 
?></title>

That’s the <title> tag, which displays the site title at the top of the browser window. How this title appears depends on which page is being viewed. Let’s break it down into sections.

For every page in your theme except the front page, we want to show the current page’s title immediately followed by a pipe separator on the right. The WordPress function wp_title() does this work for us. Immediately to the right of the pipe separator, we want to include the blog name. The handy bloginfo() function makes this possible.

We’re going to display the title a bit differently on the front page: the site title, a separator pipe, and the site description.

First we declare a variable called $site_description to store the site description so that we can use it later. In PHP, variables start with a “$”. We set $site_description equal to the value that get_bloginfo( 'description', 'display' ); returns. Notice the semi-colon (“;”) at the end. Whenever you declare a variable in PHP, be sure to end it with a semi-colon.

Next, we have a simple conditional statement that, in plain English, reads: “if the site has a site description and this is either the home page or a static front page, display the site description.”

Finally, we add page numbers on “older post” pages.

1
2
<link rel="profile" href="http://gmpg.org/xfn/11" />
<link rel="pingback" href="<?php bloginfo( 'pingback_url' ); ?>" />

The first line adds support for XFN, and the second line provides links for our pingbacks.

1
2
3
<!--[if lt IE 9]>
<script src="<?php echo get_template_directory_uri(); ?>/js/html5.js" type="text/javascript"></script>
<![endif]-->

Look, more HTML conditionals! This part loads a JavaScript file that enables old versions of Internet Explorer to recognize the new HTML5 elements, and it only loads for visitors who are using IE 8 or earlier.

Adding this part is optional. If you’d like to use the plugin, let’s set it up now. You should already have a “js” folder in your theme directory. Navigate to your js folder, and create a new file called “html5.js”. Here’s the plugin code from _s. Paste all of it into your html5.js file.

Next, we have:

1
<?php wp_head(); ?>

This is a required hook. WordPress plugins and other cool things rely on it.

 <body <?php body_class(); ?> >

The body tag for our theme. The body_class() function adds a bunch of useful CSS classes to the body tag that come in handy when we want to style the theme based on a variety of conditions. To see a live example, view the source of this page, and look for the body tag. You’ll see something like this:

1
<body class="single single-post postid-3781 single-format-standard singular">

Because we’re on a single post, we get the class “single”. Because this post is of the standard post format, we get the “post-format-standard” class. View the source of different types of views (archives, pages, the front page, search results, etc) and observe how the body classes change.

The header section

Now we want to add in our site title, which will act as a link to our home page, site description, and menu.

In header.php move down to the hgroup tags. It’s here that we’ll add in the title and description. Replace the opening and closing hgrouptags with this:

1
2
3
4
<hgroup>
     <h1 class="site-title"><a href="<?php echo home_url( '/' ); ?>" title="<?php echo esc_attr( get_bloginfo( 'name', 'display' ) ); ?>" rel="home"><?php bloginfo( 'name' ); ?></a></h1>
     <h2 class="site-description"><?php bloginfo( 'description' ); ?></h2>
</hgroup>

In the code above we’re using a WordPress Template Tag calledhome_url(). You can see we’re using it to get the main URL of our WordPress blog.

To get the name of our blog, and the description, we’re using bloginfo(). You’ll recall that we used this function earlier when printing our titletag (also notice the escaping with esc_attr() on the “title” attribute of the site title link). It can be used to get over 20 different pieces of information about your blog. It takes that information and prints it in your template. Understand this and you understand WordPress Themes. We take an HTML structure and we call WordPress Template Tags with PHP to fill it out. Simple stuff really. It’s just a matter of getting used to seeing the template tags in there, along with some IF statements and a few PHP loops (we’ll get to those too). Move on down to the nav section. We’re going to add a skip link so folks using a screen reader don’t have to suffer through our menu when they just want to get to the content. Right after <nav>, add the following:

1
2
<h1 class="assistive-text"><?php _e( 'Menu', 'shape' ); ?></h1>
<div class="assistive-text skip-link"><a href="#content" title="<?php esc_attr_e( 'Skip to content', '_s' ); ?>"><?php _e( 'Skip to content', 'shape' ); ?></a></div>

and we’re going to add the custom menu that we created in Setting Up Your Theme Functions, really couldn’t be any easier as it’s just one template tag, with only 1 argument:

1
<?php wp_nav_menu( array( 'theme_location' => 'primary' ) ); ?>

Easy, right? So your <nav> section should look like this:

1
2
3
4
5
<nav role="navigation" class="site-navigation main-navigation">
     <h1 class="assistive-text"><?php _e( 'Menu', 'shape' ); ?></h1>
     <div class="assistive-text skip-link"><a href="#content" title="<?php esc_attr_e( 'Skip to content', 'shape' ); ?>"><?php _e( 'Skip to content', 'shape' ); ?></a></div>
     <?php wp_nav_menu( array( 'theme_location' => 'primary' ) ); ?>
</nav><!-- .site-navigation .main-navigation -->

If you created multiple nav menus in functions.php, you can add them in the same manner as we have here, in the location where you want your menu to appear (and be sure to change “primary” in ‘theme_location’ => ‘primary’ to match the name of the additional menu).

We’ve got a few more things to take care of, and then we’ll be done. We’re going to get functions.php out again and add a new function to load our stylesheet and a few other JavaScript-powered goodies. Open functions.php and add the following at the end of the file.

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
/**
 * Enqueue scripts and styles
 */
function shape_scripts() {
    wp_enqueue_style( 'style', get_stylesheet_uri() );
 
    if ( is_singular() && comments_open() && get_option( 'thread_comments' ) ) {
        wp_enqueue_script( 'comment-reply' );
    }
 
    wp_enqueue_script( 'navigation', get_template_directory_uri() . '/js/navigation.js', array(), '20120206', true );
 
    if ( is_singular() && wp_attachment_is_image() ) {
        wp_enqueue_script( 'keyboard-image-navigation', get_template_directory_uri() . '/js/keyboard-image-navigation.js', array( 'jquery' ), '20120202' );
    }
}
add_action( 'wp_enqueue_scripts', 'shape_scripts' );

As you can see, we’re using wp_enqueue_style() andwp_enqueue_scripts() to load our stylesheet and JavaScript files, respectively. It’s the current best practice to use these functions to load CSS and JavaScript into themes and plugins, instead of hard-coding links into header.php.

At the end of the function, we hook shape_scripts() ontowp_enqueue_scripts(), which will dynamically add links to your stylesheet and scripts into the header.

Let’s look at the rest of the function.

1
2
3
if ( is_singular() && comments_open() && get_option( 'thread_comments' ) ) {
    wp_enqueue_script( 'comment-reply' );
}

Here, we’re loading the comment-reply.js script (which comes bundled with WordPress) that moves the comment form underneath the comment you’re replying to when you click the “reply” link. Notice how we’re only loading comment-reply.js if we’re on a single post or page, comments are open, and threaded comments are enabled. There’s no need to waste resources loading this script in places it’s not needed.

1
2
3
4
5
wp_enqueue_script( 'navigation', get_template_directory_uri() . '/js/navigation.js', array(), '20120206', true );
 
if ( is_singular() && wp_attachment_is_image() ) {
    wp_enqueue_script( 'keyboard-image-navigation', get_template_directory_uri() . '/js/keyboard-image-navigation.js', array( 'jquery' ), '20120202' );
}

Here are two optional, but neat scripts (if you don’t want to use them, just delete them from the function). The first, navigation.js, turns your main navigation menu into a nifty mobile-friendly menu on smaller screens. The second, key-board-image-navigation.js, adds the ability to navigate through images using the left and right arrow keys on your keyboard. This script only loads on single, image attachment pages.

The second script requires jQuery. Notice how we pass “jquery” as a parameter within the wp_enqueue_script() function. This tells WordPress that the script depends on jQuery. As a result, WordPress will also load the jQuery library. We don’t have to include the actual library in our theme files, because WordPress already comes bundled with multiple JavaScript libraries and default scripts. If you find other cool scripts to add to your theme in the future, just come back and add them to shape_scripts, in the same way we’ve loaded these scripts. Pretty cool, huh?

We’re almost done! If you opt to use navigation.js and keyboard-image-navigation.js, you need to add them. Go ahead and create the two files in your theme’s js folder. Here is the respective code to paste into each, grabbed from _s: navigation.js and keyboard-image-navigation.js.

And that’s it! Your WordPress Theme Header Template is search engine optimized and coded up, and your stylesheet and you’ve got a nice, clean function to load your stylesheet and other theme scripts.

WordPress 主题开发 - (八) Head模板 待翻译的更多相关文章

  1. WordPress 主题开发 - (十三) Archive模板 待翻译

    What archive.php does (and all its related templates) is show posts based on a select criteria. A da ...

  2. 黄聪:《跟黄聪学WordPress主题开发》

    又一个作品完成!<跟黄聪学Wordpress主题开发>,国内最好的Wordpress主题模版开发视频教程!! 目录预览: WordPress官方源文件层式结构讲解 WordPress数据库 ...

  3. wordpress 主题开发

    https://yusi123.com/3205.html https://themeshaper.com/2012/10/22/the-themeshaper-wordpress-theme-tut ...

  4. [转]WordPress 主题教程 #2:模板文件和模板

    本文转自:http://blog.wpjam.com/m/wp-theme-lesson-2-template-files-and-templates/ 模板文件(template files)和模板 ...

  5. WordPress 主题开发 - (三) 开发工具 待翻译

    Before we get started building any WordPress Theme, we’re going to need to get our development tools ...

  6. WordPress 主题开发 - (一) 前言 待翻译

    原文出自: http://themeshaper.com/2012/10/22/the-themeshaper-wordpress-theme-tutorial-2nd-edition/ THE TH ...

  7. WordPress 主题开发:从入门到精通(必读)

    本专栏介绍如何开发设计你自己的 WordPress 主题.如果你希望了解更多如何安装和应用主题的内容,请参阅应用主题文档.本文的内容不同于应用主题,因为所讨论的是编写代码去构建你自己的主题的技术内容, ...

  8. [转]WordPress主题开发:主题初始化

    本文转自:http://www.cnblogs.com/tinyphp/p/4391182.html 在最简单的情况下,一个WordPress主题由两个文件构成: index.php -------- ...

  9. WordPress主题开发:主题初始化

    在最简单的情况下,一个WordPress主题由两个文件构成: index.php ------------------主模版 style.css  -------------------主样式表(注意 ...

随机推荐

  1. poj 2109 Power of Cryptography

    点击打开链接 Power of Cryptography Time Limit: 1000MS   Memory Limit: 30000K Total Submissions: 16388   Ac ...

  2. nyoj 76 超级台阶

    点击打开链接 超级台阶 时间限制:1000 ms  |  内存限制:65535 KB 难度:3 描述 有一楼梯共m级,刚开始时你在第一级,若每次只能跨上一级或二级,要走上第m级,共有多少走法? 注:规 ...

  3. (整理).net实现条形码与二维码

    本文由来源网络的知识点组合而成,感谢分享的作者,文章结尾处给出查询资料连接. 条形码(barcode)是将宽度不等的多个黑条和空白,按照一定的编码规则排列,用以表达一组信息的图形标识符.常见的条形码是 ...

  4. 初探接口测试框架--python系列4

    点击标题下「蓝色微信名」可快速关注 坚持的是分享,搬运的是知识,图的是大家的进步,没有收费的培训,没有虚度的吹水,喜欢就关注.转发(免费帮助更多伙伴)等来交流,想了解的知识请留言,给你带来更多价值,是 ...

  5. [Mongo] 简单的操作命令

    1. 连接服务器: mongo 2. 连接数据库 use dbname 3. 查询所有集合的名字 db.getCollectionNames() 4. 查询某集合的数据 db.collection.f ...

  6. 如何为 Drupal 7 网站添加悬浮的反馈按钮?

    最近有客户咨询我们要怎么为 Drupal 网站添加悬浮按钮,方便访客能够链接到反馈表单页面.很幸运,使用 Feedback Simple 模块可以很容易实现. 在这篇短教程中,我将和大家分享如何添加链 ...

  7. 为什么你不应该自行更新 Drupal 网站?

    (译注:这篇文章主要还是针对于非专业人员及个人Drupal站长,对于专业的 Drupal 团队和公司而言 Drupal 的升级更新都有规范的操作流程,完全是家常便饭,不可能出现文中出现的这些情况.尽管 ...

  8. JFrame 不规则窗体

    效果截图: 这几天静心学java,由于学的不是很好,也没有什么有什么可以作品,但是毕竟也算刚开始认真学,也遇到了好多问题: 首先 1. JFrame的无边框设置:JFrame.setUndecorat ...

  9. Laxcus大数据管理系统2.0(10)- 第八章 安全

    第八章 安全 由于安全问题对大数据系统乃至当前社会的重要性,我们在Laxcus 2.0版本实现了全体系的安全管理策略.同时我们也考虑到系统的不同环节对安全管理的需求是不一样的,所以有选择地做了不同的安 ...

  10. 学习opencv跟轮廓相关的

    查找轮廓 轮廓到底是什么?一个轮廓一般对应一系列的点,也就是图像中的一条曲线.表示的方法可能根据不同情况而有所不同.有多重方法可以表示曲线.在openCV中一般用序列来存储轮廓信息.序列中的每一个元素 ...