WordPress 主题开发 - (八) Head模板 待翻译
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模板 待翻译的更多相关文章
- WordPress 主题开发 - (十三) Archive模板 待翻译
What archive.php does (and all its related templates) is show posts based on a select criteria. A da ...
- 黄聪:《跟黄聪学WordPress主题开发》
又一个作品完成!<跟黄聪学Wordpress主题开发>,国内最好的Wordpress主题模版开发视频教程!! 目录预览: WordPress官方源文件层式结构讲解 WordPress数据库 ...
- wordpress 主题开发
https://yusi123.com/3205.html https://themeshaper.com/2012/10/22/the-themeshaper-wordpress-theme-tut ...
- [转]WordPress 主题教程 #2:模板文件和模板
本文转自:http://blog.wpjam.com/m/wp-theme-lesson-2-template-files-and-templates/ 模板文件(template files)和模板 ...
- WordPress 主题开发 - (三) 开发工具 待翻译
Before we get started building any WordPress Theme, we’re going to need to get our development tools ...
- WordPress 主题开发 - (一) 前言 待翻译
原文出自: http://themeshaper.com/2012/10/22/the-themeshaper-wordpress-theme-tutorial-2nd-edition/ THE TH ...
- WordPress 主题开发:从入门到精通(必读)
本专栏介绍如何开发设计你自己的 WordPress 主题.如果你希望了解更多如何安装和应用主题的内容,请参阅应用主题文档.本文的内容不同于应用主题,因为所讨论的是编写代码去构建你自己的主题的技术内容, ...
- [转]WordPress主题开发:主题初始化
本文转自:http://www.cnblogs.com/tinyphp/p/4391182.html 在最简单的情况下,一个WordPress主题由两个文件构成: index.php -------- ...
- WordPress主题开发:主题初始化
在最简单的情况下,一个WordPress主题由两个文件构成: index.php ------------------主模版 style.css -------------------主样式表(注意 ...
随机推荐
- SQLSERVER:计算数据库中各个表的数据量和每行记录所占用空间
转:http://www.cnblogs.com/lyhabc/p/3828496.html CREATE TABLE #tablespaceinfo ( nameinfo ) , rowsinfo ...
- nginx 添加perl
首先,要知道你原安装的nginx版本,以及原来安装的模块,用nginx -V即可 /usr/sbin/nginx -V 结尾处的--add-module 重新安装时这里可以去掉, 然后去官网下载一个相 ...
- .NET基础操作回顾_使用ADO.NET操作SqlServer使用的类
有些工具用的久了或者有新工具出现后,就慢慢的遗忘了很多,它们从熟悉的变成陌生,当然,对于我们来说不是好事吧. 今天回顾一下ADO.NET用到的MS的基础类库,先上代码(标准的SqlServer操作) ...
- Skill
Skill Yasser is an Egyptian coach; he will be organizing a training camp in Jordan. At the end of ca ...
- Cocos2dx3.0过渡篇 各种遍历与范围for语句的使用【转】
1.CCArray的遍历看到这里,有些人又按耐不住的要举起西瓜刀了:你不是说3.0beta后已经没有CCArray这货了吗?现在又拿出来作甚?其实我也很无辜,CCArray确实是没了,但在某个不为人知 ...
- cocos2d-x 中 TTF 字体文件的位置
cocos2d-x 中,字体文件需要保存在 fonts 文件夹中,如果字体路径中没有 fonts/ 会自动添加上这个文件夹. 如果字体名称没有 .ttf 后缀,也会自动加上这个后缀. unsigned ...
- python-appium手机自动化测试(仅需安装包)前期准备(pydev-eclipse编辑器)
1.jdk安装与环境变量配置教程http://jingyan.baidu.com/article/6dad5075d1dc40a123e36ea3.html 我本机安装的是1.6.043 2.sdk下 ...
- Laxcus大数据管理系统2.0(2)- 第一章 基础概述 1.1 基于现状的一些思考
第一章 基础概述 1.1 基于现状的一些思考 在过去十几年里,随着互联网产业的普及和高速发展,各种格式的互联网数据也呈现爆炸性增长之势.与此同时,在数据应用的另一个重要领域:商业和科学计算,在各种新兴 ...
- 华为OJ平台——DNA序列
题目描述: 一个DNA序列由A/C/G/T四个字母的排列组合组成.G和C的比例(定义为GC-Ratio)是序列中G和C两个字母的总的出现次数除以总的字母数目(也就是序列长度).在基因工程中,这个比例非 ...
- MVC ckeditor的基本使用
之前在自己的WebForm练习项目里面用到过ckeditor,时隔蛮久后,今天再一次把ckeditor运用到MVC里面,用于最近着手开发的企业站的新闻动态的内容之新增与修改. 找到的资料都说要把下载的 ...