本文主要通过分析 WordPress 官方主题 twentytwelve 的中的“顶部模板”来了解 WordPress 主题顶部制作需要用到的函数。

顶部模板的代码将应用于 Wordpress 所有的页面,其他页模板需要通过 get_header() 来调用。

<!DOCTYPE html>
<!--[if IE 7]>
<html class="ie ie7" <?php language_attributes(); ?>>
<![endif]-->
<!--[if IE 8]>
<html class="ie ie8" <?php language_attributes(); ?>>
<![endif]-->
<!--[if !(IE 7) | !(IE 8)  ]><!-->
<html <?php language_attributes(); ?>>
<!--<![endif]-->
<head>
<meta charset="<?php bloginfo( 'charset' ); ?>" />
<meta name="viewport" content="width=device-width" />
<title><?php wp_title( '|', true, 'right' ); ?></title>
<link rel="profile" href="http://gmpg.org/xfn/11" />
<link rel="pingback" href="<?php bloginfo( 'pingback_url' ); ?>" />
<?php // Loads HTML5 JavaScript file to add support for HTML5 elements in older IE versions. ?>
<!--[if lt IE 9]>
<script src="<?php echo get_template_directory_uri(); ?>/js/html5.js" type="text/javascript"></script>
<![endif]-->
<?php wp_head(); ?>
</head>

language_attributes():显示页面的语言,例如中文版的则显示 lang="zh-CN"
bloginfo():获取 Wordpress 相关的属性并输出,例如参数为 charset 则返回编码,pingback_url 返回 pingback 的地址。
wp_title():获取页面的标题。
get_template_directory_uri():获取模板目录的地址。
wp_head():获取 Wordpress 自动生成的一些信息。

<body <?php body_class(); ?>>
<div id="page" class="hfeed site">
    <header id="masthead" class="site-header" role="banner">
        <hgroup>
            <h1 class="site-title"><a href="<?php echo esc_url( 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>

        <nav id="site-navigation" class="main-navigation" role="navigation">
            <h3 class="menu-toggle"><?php _e( 'Menu', 'twentytwelve' ); ?></h3>
            <a class="assistive-text" href="#content" title="<?php esc_attr_e( 'Skip to content', 'twentytwelve' ); ?>"><?php _e( 'Skip to content', 'twentytwelve' ); ?></a>
            <?php wp_nav_menu( array( 'theme_location' => 'primary', 'menu_class' => 'nav-menu' ) ); ?>
        </nav><!-- #site-navigation -->

        <?php $header_image = get_header_image();
        if ( ! empty( $header_image ) ) : ?>
            <a href="<?php echo esc_url( home_url( '/' ) ); ?>"><img src="<?php echo esc_url( $header_image ); ?>" class="header-image" width="<?php echo get_custom_header()->width; ?>" height="<?php echo get_custom_header()->height; ?>" alt="" /></a>
        <?php endif; ?>
    </header><!-- #masthead -->

    <div id="main" class="wrapper">

body_class():设置 body 的 class 属性,不同的页面属性值会不一样。
home_url():获取博客首页的地址。
esc_url():过滤 URL。
get_bloginfo():和 bloginfo() 作用一样,获取博客相关信息,但是这里只获取值不输出。
wp_nav_menu():获取导航菜单。之前已经写过如何自定义导航菜单
get_header_image():获取自定义顶部图像的地址。在“后台-外观-顶部”里设置。
get_custom_header():获取自定义顶部对象。

值得注意的是,想要主题有导航菜单和自定义顶部的功能,需要在 function.php 里注册。

标签: