WordPress 主题开发 - (八) Head模板 待翻译

时间:2022-03-02 21:59:35

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.