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. px、pt、in、dp、dpi

        PPI 与 DPI ppi的运算方式是:PPI = √(长度像素数² + 宽度像素数²) / 屏幕对角线英寸数.即:长.宽各自平方之和的开方,再除以屏幕对角线的英寸数. 以iphone5为例, ...

  2. js注意事项

    在数组顶部插入一条数据 data.result.unshift({ Value: 'all', Text: '请选择分类' }); 执行iframe中的javascript方法 window.fram ...

  3. ms sqlserver 系列之如何查看数据链接数

    [转]如何查看SQL SERVER数据库当前连接数 1.通过管理工具开始->管理工具->性能(或者是运行里面输入mmc)然后通过添加计数器添加 SQL 的常用统计然后在下面列出的项目里面选 ...

  4. LayoutInflater.Factory的夜间模式

    自定义实现个Factory,可以用来解析自定义的属性.public interface Factory { /** * Hook you can supply that is called when ...

  5. HDFS Java API 常用操作

    package com.luogankun.hadoop.hdfs.api; import java.io.BufferedInputStream; import java.io.File; impo ...

  6. Hive基础之自定义封装hivefile命令

    存在的问题:当把hql写到shell中,不方便阅读:但把hql写到文件中,又传递不了参数:怎么办呢? 自定义hivefile 执行方式形如: 第一个参数为要执行的hql文件,后续的参数为要替换的key ...

  7. Flask框架学习笔记(API接口管理平台 V1.0)

    今天博主终于完成了API接口管理平台,最后差的就是数据库的维护, 博主这里介绍下平台的设计原理,首先基于python,利用flask的web框架+bootstrap前端框架完成,先阶段完成了前台展示页 ...

  8. 安装python的redis模块

    wget --no-check-certificate https://pypi.python.org/packages/source/r/redis/redis-2.8.0.tar.gz tar - ...

  9. 洛谷P2722 总分 Score Inflation

    P2722 总分 Score Inflation 184通过 295提交 题目提供者该用户不存在 标签USACO 难度普及- 提交  讨论  题解 最新讨论 关于算法 题目背景 学生在我们USACO的 ...

  10. asp.net(c#)中如何在前端用js写条件查询,且不用调用存储过程

    前端页面(源): <dx:ASPxButton ID="ASPxButton_Select" runat="server" Text="查询&q ...