[隐藏]

一、Anatomy of a Theme

1、模板文件夹放置在 “ wp-content/themes/ ” 路径下;

2、所有模板文件都放置到模板文件夹里(holds all of the Theme’s stylesheet files, template files, and optional functions file (functions.php), JavaScript files, and images.);

ps:研究wp的默认模板对学习模板制作有帮助(The anatomy of a WordPress theme 附于后)。

3、wp模板包括3个基本的文件:css文件(style.css)、wp模板文件(控制wp页面如何显示数据)、可选的函数(functions.php,做为主题文件的一部分)。

1)主题层叠样式文件(theme stylesheet —— style.css):

例: ”Twenty Ten”主题css文件的头部代码如下:

/*
Theme Name: Twenty Ten
Theme URI: http://wordpress.org/
Description: The 2010 default theme for WordPress.
Author: wordpressdotorg
Author URI: http://wordpress.org/
Version: 1.0
Tags: black, blue, white, two-columns, fixed-width, custom-header, custom-background, threaded-comments, sticky-post, translation-ready, microformats, rtl-language-support, editor-style, custom-menu (optional)

License:
License URI:

General comments (optional).
*/

NB(nota bene):建议Author用作者在 wordpress.org 的用户名;tags 是描述模板的关键词,便于用户搜索(建议的关键词参看:http://wordpress.org/extend/themes/tag-filter/)。

css的头部描述(The comment header lines in style.css)是必须的,便于wp将模板显示在 wp主题管理界面:Administration Panel  Design > Themes

2)功能函数(Functions File —— functions.php):

这个文件的功能类似插件(plugin),在wp初始化的时候会自动引导。建议在以下及各方面使用:

  • 激活类似 “侧边栏、导航菜单、文章缩略图、小工具、文章形式、自定义背景、自定义顶部、编辑器用样式、自动 Feed 链接”  等主题特性( Theme Features );
  • 在主题的多个模板中使用功能函数;
  • 设置选项菜单,让站点所有者可以选择颜色、样式等其他主题部分。

note:因为函数文件类似plugin,所以 Theme Features 是你了解可以做什么的信息的最好的地方。

3)模板文件(Template Files):

模板是php的源码,用来将用户请求的页面输出为html。模板文件由html、php、WordPress Template Tags 构成。你可以为不同的部分制定不同的模板,也可以使用一个 index.php 文件做为所有页面的公用模板。

模板文件列表(Template Files List):

这里是被wp识别的模板文件,当然,你的主题可以包含其他css、图片等文件,但是这里的文件是wp的特别定义的文件。可以通过  Template Hierarchy 了解更多信息。

style.css —— The main stylesheet. This must be included with your Theme, and it must contain the information header for your Theme.

rtl.css —— The rtl stylesheet. This will be included automatically if the website’s text direction is right-to-left. This can be generated using thethe RTLer plugin.

index.php —— The main template. If your Theme provides its own templates, index.php must be present.

comments.php —— The comments template.

front-page.php —— The front page template, it is only used if you use a static front page.

home.php —— The home page template, which is the front page by default. If you use a static front page this is the template for the page with the latest posts.

single.php —— The single post template. Used when a single post is queried. For this and all other query templates, index.php is used if the query template is not present.

single-{post-type}.php —— The single post template used when a single post from a custom post type is queried. For example, single-books.php would be used for displaying single posts from the custom post type named “books”. index.php is used if the query template for the custom post type is not present.

page.php —— The page template. Used when an individual Page is queried.

category.php —— The category template. Used when a category is queried.

tag.php —— The tag template. Used when a tag is queried.

taxonomy.php —— The term template. Used when a term in a custom taxonomy is queried.

author.php —— The author template. Used when an author is queried.

date.php —— The date/time template. Used when a date or time is queried. Year, month, day, hour, minute, second.

archive.php —— The archive template. Used when a category, author, or date is queried. Note that this template will be overridden by category.php,author.php, and date.php for their respective query types.

search.php —— The search results template. Used when a search is performed.

attachment.php —— Attachment template. Used when viewing a single attachment.

image.php —— Image attachment template. Used when viewing a single image attachment. If not present, attachment.php will be used.

404.php —— The 404 Not Found template. Used when WordPress cannot find a post or page that matches the query.

基本模板文件

  • style.css
  • index.php

典型的模板文件还包括(Typical template files include):

  • comments.php
  • comments-popup.php
  • footer.php
  • header.php
  • sidebar.php

你可以使用标签(tags)将这些模板文件放置(包含)到 index.php 文件里你需要使用的地方。

包含这些文件的范例:

<?php get_sidebar(); ?>

<?php get_footer(); ?>

The default files for some template functions may be deprecated or not present, and you should provide these files in your theme. As of version 3.0, the deprecated default files are located in wp-includes/theme-compat. For example, you should provide header.php for the function get_header() to work safely, and comments.php for the function comments_template().

For more on how these various Templates work and how to generate different information within them, read the Templates documentation.

二、自定制页面模板(Custom Page Templates)

宋注:只对页面有效,可以用于制作活动专题页面。

让我们将我们自定制的第一个模板文件取名 snarfer.php ,并在其中放置如下代码:

<?php
/*
Template Name: Snarfer
*/
?>

这些代码定义这个  snarfer.php 文件为 “ Snarfer ” 模板,“ Snarfer ” 这个名字也可以换着别的名字,这个名字将在主题编辑器(Theme Editor)里显示为这个模板的编辑连接。这个php文件的名字可以使用任何与保留主题文件名( reserved Theme filenames )不一样的其他名字。

你接下来写的代码将决定使用 “ Snarfer ” 页面模板的页面的显示。你可以使用的wp模板函数变量请参看:Template Tags。你会发现从别的模板文件(比如 page.php 或者 index.php)拷贝内容到 snarfer.php,然后在文件的顶部加上上面的5行代码非常方便。这样,你只需要修改修改html和php代码,而不是从一无所有开始。一旦你创建好这个页面模板文件,并且将他放置到主题目录,在你创建和编辑页面的时候将会看到这个选择。(Note:在你完成上面的工作之前,创建和编辑页面的时候不会显示这个页面模板选项。)

三、基于查询的模板文件(Query-based Template Files)

wp可以为不同的查询类型引导不同的模板。有两种方式可以实现:一是做为内建模板等级结构( Template Hierarchy)的一部分;二是通过使用模板文件里循环( loop )里面的条件标签。

要使用模板等级结构( Template Hierarchy),需要提供特定的模板文件,他将自动覆写 index.php 文件。比如,如果你的主题提供了一个 category.php 文件,并且有个一分类(category)正被用户查询,那么 category.php 将被引导来代替 index.php,如果  category.php 文件没有,那么系统就会使用index.php。

你还可以通过提供一个符合模板等级结构规则的文件命名实现更进一步的定制。例如:命名为 category-6.php 的模板文件将会在生成 ID 为6的分类页面的时候优先于 category.php 使用,分类的 ID 数值可以在管理员登陆后台后的 “管理 > 分类( Manage > Categories)” 里面找到(在分类管理页面,鼠标移动到相应分类的操作项目上就会显示,比如:“编辑”、“删除” 链接:http://localhost/laosong_wp/wp-admin/edit-tags.php?action=edit&taxonomy=category&tag_ID=1&post_type=post、或者 “查看” 链接:http://localhost/laosong_wp/?cat=1 )。更多信息,查看分类模板Category Templates)。

如果需要比模板等级结构( Template Hierarchy)中提供的模板文件更深入的控制,我们可以使用条件标签Conditional Tags)。条件标签的原理是检查在wp循环WordPress Loop)中特定的条件是否为真(true),然后你可以调用特定的模板,或者根据条件在屏幕上输出特定的文本。

例如,仅为特定分类中的一个文章生成一个个性化的样式(css),代码如下:

<?php
if ( is_category( '9' ) ) {
    get_template_part( 'single2' ); // looking for posts in category with ID of '9'
} else {
    get_template_part( 'single1' ); // put this on every other category post
}
?>

或者,使用一个查询,使用下面这样的代码:

<?php
$post = $wp_query->post;
if ( in_category( '9' ) ) {
    get_template_part( 'single2' );
} else {
    get_template_part( 'single1' );
}
?>

在任何的情况下,这个范例代码将可实现特定文章的分类使用不同的模板生成页面,查询条件不仅限于分类,查看条件标签Conditional Tags)可以了解所有的选项。

定义自定义模板(Defining Custom Template

使用WordPress的插件系统可以实现根据自定义条件来指定额外的模板。这种高级功能可以通过使用“ 模板重定向(template_redirect) ”动作挂钩action hook)。有关创建插件的更多信息,可以发现在插件API参考。More information about creating plugins can be found in the Plugin API reference.

包含模板文件(Including Template Files)

在模板里面调用其他的模板(除了 header, sidebar, footer,这些模板文件已经有类似 get_header() 这样的预设好的包含命令),你可以使用 get_template_part(),这使代码块的重用变得容易。

从模板引用文件(Referencing Files From a Template

当从同一个主题引用其他文件时,不要对 URIs(通用资源标识符:Uniform Resource Identifier, 简称”URI”) 和文件路径硬编码,而应该通过 bloginfo() 引用 URIs 和文件路径 。 请参看 Referencing Files From a Template

注意:层叠样式表中的 URIs 是相对别的样式表文件,不是页面引用样式表的 URIs。例如:如果你想包含一个主题里的图片文件 images/my-background.jpg ,那么只需要在css里指定相对路径 ,象这样:

h1 {
    background-image: url(images/my-background.jpg);
}

插件 API 钩子(Plugin API Hooks)

When developing Themes, it’s good to keep in mind that your Theme should be set up so that it can work well with any WordPress plugins users might decide to install. Plugins add functionality to WordPress via “Action Hooks” (see Plugin API for more information).

Most Action Hooks are within the core PHP code of WordPress, so your Theme does not have to have any special tags for them to work. But a few Action Hooks do need to be present in your Theme, in order for Plugins to display information directly in your header, footer, sidebar, or in the page body. Here is a list of the special Action Hook Template Tags you need to include:

wp_head()
Goes in the <head> element of a theme, in header.php. Example plugin use: add JavaScript code.
wp_footer()
Goes in footer.php, just before the closing </body> tag. Example plugin use: insert PHP code that needs to run after everything else, at the bottom of the footer. Very commonly used to insert web statistics code, such as Google Analytics.
wp_meta()
Typically goes in the <li>Meta</li> section of a Theme’s menu or sidebar; sidebar.php template. Example plugin use: include a rotating advertisement or a tag cloud.
comment_form()
Goes in comments.php directly before the file’s closing tag (</div>). Example plugin use: display a comment preview.

For a real world usage example, you’ll find these plugin hooks included in the default Theme’s templates.

自定制主题API(Theme Customization API)

wp3.4开始,几乎所有主题默认状态下都可以使用新出现的主题自定制功能。主题自定制管理页面会自动显示主题中声明支持 add_theme_support() 或使用设置API (Settings API) 的选项,并且允许管理员实时看到临时的修改呈现。

Theme and plugin developers interested in adding new options to a theme’s Theme Customization page should see the documentation on the Theme Customization API. Additional tutorials on the Theme Customization API are available at theOttopress.com website.

Untrusted Data

You should escape dynamically generated content in your Theme, especially content that is output to HTML attributes. As noted inWordPress Coding Standards, text that goes into attributes should be run through esc_attr() so that single or double quotes do not end the attribute value and invalidate the XHTML and cause a security issue. Common places to check are titlealt, andvalue attributes.

There are few special template tags for common cases where safe output is needed. One such case involves outputing a post title to a title attribute using the_title_attribute() instead of the_title() to avoid a security vulnerability. Here’s an example of correct escaping for the title attribute of a post title link when using translatable text:

<a href="<?php the_permalink(); ?>" title="<?php sprintf( __( 'Permanent Link to %s', 'theme-name' ), the_title_attribute( 'echo=0' ) ); ?>"><?php the_title(); ?></a>

Replace deprecated escape calls with the correct calls: wp_specialchars() and htmlspecialchars() with esc_html(),clean_url() with esc_url(), and attribute_escape() with esc_attr(). See Data_Validation for more.

Translation Support / I18n

To ensure smooth transition for language localization, use the WordPress gettext-based i18n functions for wrapping all translatable text within the template files. This makes it easier for the translation files to hook in and translate the labels, titles and other template text into the site’s current language. See more at WordPress Localization and I18n for WordPress Developers.

Theme Classes

Implement the following template tags to add WordPress-generated class attributes to body, post, and comment elements. For post classes, apply only to elements within The Loop.

Template File Checklist

When developing a Theme, check your template files against the following template file standards.

Document Head (header.php)

  • Use the proper DOCTYPE.
  • The opening <html> tag should include language_attributes().
  • The <meta> charset element should be placed before everything else, including the <title> element.
  • Use bloginfo() to set the <meta> charset and description elements.
  • Use wp_title() to set the <title> element. See why.
  • Use get_stylesheet_uri() to get the URL of the current theme stylesheet.
  • Use Automatic Feed Links to add feed links.
  • Add a call to wp_head() before the closing </head> tag. Plugins use this action hook to add their own scripts, stylesheets, and other functionality.

Here’s an example of a correctly-formatted HTML5 compliant head area:

<!DOCTYPE html>
<html <?php language_attributes(); ?>>
    <head>
        <meta charset="<?php bloginfo( 'charset' ); ?>" />
        <title><?php wp_title(); ?></title>
        <meta name="description" content="<?php bloginfo( 'description' ); ?>">
        <link rel="profile" href="http://gmpg.org/xfn/11" />
        <link rel="stylesheet" href="<?php echo get_stylesheet_uri(); ?>" type="text/css" media="screen" />
        <link rel="pingback" href="<?php bloginfo( 'pingback_url' ); ?>" />
        <?php if ( is_singular() && get_option( 'thread_comments' ) ) wp_enqueue_script( 'comment-reply' ); ?>
        <?php wp_head(); ?>
    </head>
  • The Theme’s main navigation should support a custom menu with wp_nav_menu().
    • Menus should support long link titles and a large amount of list items. These items should not break the design or layout.
    • Submenu items should display correctly. If possible, support drop-down menu styles for submenu items. Drop-downs allowing showing menu depth instead of just showing the top level.

Widgets (sidebar.php)

  • The Theme should be widgetized as fully as possible. Any area in the layout that works like a widget (tag cloud, blogroll, list of categories) or could accept widgets (sidebar) should allow widgets.
  • Content that appears in widgetized areas by default (hard-coded into the sidebar, for example) should disappear when widgets are enabled from Appearance > Widgets.
  • Use the wp_footer() call, to appear just before closing body tag.
<?php wp_footer(); ?>
</body>
</html>

Index (index.php)

  • Display a list of posts in excerpt or full-length form. Choose one or the other as appropriate.
  • Include wp_link_pages() to support navigation links within posts.

Archive (archive.php)

  • Display archive title (tag, category, date-based, or author archives).
  • Display a list of posts in excerpt or full-length form. Choose one or the other as appropriate.
  • Include wp_link_pages() to support navigation links within posts.

Pages (page.php)

  • Display page title and page content.
  • Display comment list and comment form (unless comments are off).
  • Include wp_link_pages() to support navigation links within a page.
  • Metadata such as tags, categories, date and author should not be displayed.
  • Display an “Edit” link for logged-in users with edit permissions.

Single Post (single.php)

  • Include wp_link_pages() to support navigation links within a post.
  • Display post title and post content.
    • The title should be plain text instead of a link pointing to itself.
  • Display the post date.
  • Display the author name (if appropriate).
  • Display post categories and post tags.
  • Display an “Edit” link for logged-in users with edit permissions.
  • Display comment list and comment form.
  • Show navigation links to next and previous post using previous_post_link() and next_post_link().

Comments (comments.php)

  • Author comment should be highlighted differently.
  • Display gravatars (user avatars) if appropriate.
  • Support threaded comments.
  • Display trackbacks/pingbacks.
  • This file shouldn’t contain function definitions unless in the function_exist() check to avoid redeclaration errors. Ideally all functions should be in functions.php.
  • Display a list of posts in excerpt or full-length form. Choose one or the other as appropriate.
  • The search results page show the search term which generated the results. It’s a simple but useful way to remind someone what they just searched for — especially in the case of zero results. Use the_search_query() or get_search_query() (display or return the value, respectively). For example:
    <h2><?php printf( __( 'Search Results for: %s' ), '<span>' . get_search_query() . '</span>'); ?></h2>
  • It’s a good practice to include the search form again on the results page. Include it with: get_search_form().

JavaScript

  • JavaScript code should be placed in external files whenever possible.
  • Use wp_enqueue_script() to load your scripts.
  • JavaScript loaded directly into HTML documents (template files) should be CDATA encoded to prevent errors in older browsers.
<script type="text/javascript">
/* <![CDATA[ */
// content of your Javascript goes here
/* ]]> */
</script>

Screenshot

Create a screenshot for your theme. The screenshot should be named screenshot.png, and should be placed in the top level directory. The screenshot should accurately show the theme design and saved in PNG format. The recommended image size is 600×450. The screenshot will only be shown as 300×225, but the double-sized image allows for high-resolution viewing on HiDPI displays.

Theme Options

Themes can optionally support the Theme Options Screen. For an example code, see A Sample WordPress Theme Options Page.

When enabling the availability of the Theme Options Screen for a user role, use the “edit_theme_options” user capability instead of the “switch_themes” capability unless the user role actually should also be able to switch the themes. See more at Roles and Capabilities and Adding Administration Menus.

If you are using the “edit_themes” capability anywhere in your Theme to gain the Adminstrator role access to the Theme Options Screen (or maybe some custom screens), be aware that since Version 3.0, this capability is not assigned to the Adminstrator role by default in the case of WordPress Multisite installation. See the explanation. In such a case, use the “edit_theme_options” capability instead if you want the Adminstrator to see the “Theme Options” menu. See the additional capabilities of Adminstrator role when using WordPress Multisite.

Theme Testing Process

  1. Fix PHP and WordPress errors. Add the following debug setting to your wp-config.php file to see deprecated function calls and other WordPress-related errors: define('WP_DEBUG', true);. See Deprecated Functions Hook for more information.
  2. Check template files against Template File Checklist (see above).
  3. Do a run-through using the Theme Unit Test.
  4. Validate HTML and CSS. See Validating a Website.
  5. Check for JavaScript errors.
  6. Test in all your target browsers. For example, IE7, IE8, IE9, Safari, Chrome, Opera, and Firefox.
  7. Clean up any extraneous comments, debug settings, or TODO items.
  8. See Theme Review if you are publicly releasing the Theme by submitting it to the Themes Directory.

Resources and References

Code Standards

Theme Design

CSS

Templates

Functions listing

Testing and QA

Release & Promotion

External Resources & Tutorials

===========================

The anatomy of a WordPress theme

http://yoast.com/wordpress-theme-anatomy/

With all the WordPress theme frameworks that arose over the past few years, you’d almost forget what a normal WordPress theme looks like. Almost, because Yoast has got your back and we’re about to remind you! Check out our anatomy of a WordPress theme infographic:

anatomy-wordpress-yoast

For reference, here is the copy in the infographic:

Anatomy of a WordPress theme

The cheatsheet for how your blog works

WordPress themes are made up of a folder of template files, each of which controls a specific piece of your theme. Parts of your site that remain static no matter what page you’re on are controlled by header, sidebar and footer files. You can hack these files so they detect what page you are on and serve different content accordingly, such as display different navigation on posts than on pages; however it is most common for these sections to look the same throughout the site.

  • header.php Global file that displays headers and navigation. Also contains HTML code.
  • The Loop The display of contents of the main area of your site are controlled by individual WordPress theme template files using what’s called “the loop”.
  • sidebar.php Sidebar display is controlled in this file. Multiple sidebars can be set up in functions.php, and contents of sidebar widgets are set up from the WordPress wp-admin panel.
  • footer.php Contains instructions for global footer and closes HTML tags.

index.php – home

The index file controls what the homepage of your WordPress theme looks like. By default it is a loop that queries and then displays the most recent blog posts, with a link in the bottom to view previous posts.

Alternately, you can specify in wp-admin -> settings -> reading to have the home page be a page you created yourself in WordPress. In that case, you specify a different page/URL for the regular blog posts to appear on, and that page is generated by index.php.

single.php – individual posts

The display of individual posts in your WordPress theme is controlled by a little file called single.php. It contains a loop that queries just one post and displays it.

You can specify if you want sidebars (and which you want), if you want it to look different than the other pages on the site.

page.php – individual pages

Page.php controls what pages look like. You can choose to eliminate sidebars or other elements, add other unique elements for pages alone.

WordPress also allows you to create different page templates within your WordPress theme for different types of pages. To create a page template, simply copy page.php, rename it to whatever you want, then add this code to the top:

1 <?php
2 /*
3 Template Name: YourPageNameHere
4 */
5 ?>

archive.php, category.php, tag.php – archives

You can control the look and feel of different archives using template files also. If there is no archive file, the archives will look like index.php; however you can create an archive.php to override that. If you create a file called category.php, it will override archive.php for categories only. If you create a tag.php, you can override it for tag archives only.

The Loop

The loop is perhaps the most powerful part of your WordPress theme. It starts with a query (which determines which posts or pages to grab), and ends with a PHP “endwhile” statement. Everything in between is up to you. You can specify the output of titles, post content, metadata, custom fields and commenting all within the loop and each element is output for each post or page until the query is done. You can set up multiple loops and queries on a single page; for example: on a single.php you could have the loop showing the entire content of a single post, with a loop outputting just titles and thumbnails for related posts below it.

  • Query post or page
  • Start Loop
  • the_title (outputs the title of the post)
  • the_excerpt (outputs the post excerpt)
  • the_content (outputs the full post content)
  • the_category (outputs the post categories)
  • the_author (outputs the post author)
  • the_date (outputs the post date)
  • other tags (there is a variety of other tags you can use in the loop)
  • endwhile;
  • Exit the loop

Background files of a WordPress theme

In order for a WordPress theme to work, it needs a few essential background files. These files can be modified to your needs and can quite powerfully affect the custom look and functionality of your site.

comments.php

This controls the output of comments, which can be included in the loop if you desire comments on your theme. Comments.php can be overriden by plugins such as Disqus, which then take over comment functionality on your blog.

functions.php

Functions.php allows you to put your own custom PHP code in order to modify core elements of your theme. It is often used to specify multiple sidebars, change the number of characters in the excerpt or add custom admin panel options for wp-admin.

style.css

This is the main CSS stylesheet for your theme. It also contains text at the top which tells WordPress what the name of your WordPress theme is, who the author is and what the URL of your site is.