WordPress 中文文档

The Loop in Action

出自WordPress Chinese 中文文档

跳转到: 导航, 搜索

目录

Introduction

The Loop is a term that refers to the main process of WordPress. You use The Loop in your template files to show posts to visitors. You could make templates without The Loop, but you'd only be able to display data from one post.

The first thing WordPress does is check that all the files it needs are present. Next, it collects the default settings, as defined by the blog administrator, from the database. This includes things like the number of posts to display per page, whether commenting is enabled, and the like. Once these defaults are established, WordPress checks to see what the user asked for. This information is used to determine which posts to fetch from the database.

If the user didn't ask for a specific post, category, page, or date, WordPress uses the previously collected default values to determine which posts to prepare for the user. For example, if the blog administrator has selected to display 5 posts per page in Administration Settings Reading, then WordPress will fetch the five most recent posts from the database. If the user did ask for a specific post, category, page, or date, then WordPress will use that information to specify which post(s) to fetch from the database.

Once all this is done, WordPress connects to the database, retrieves the specified information, and stores the results in a variable. It is The Loop that accesses this variable, and uses the values for display in your templates.

By default, if the visitor did not select a specific post, page, category, or date, WordPress uses ttindex.php/tt to display everything. For the first part of this discussion of The Loop we'll focus only on ttindex.php/tt, and the default display of your blog. Later on, once you understand how things work, we'll investigate tricks with The Loop in other template files.

The World's Simplest Index Page

The following is a fully functional index which will display the contents (and just the contents) of each post, according to the conditions used to prepare The Loop. The only purpose for showing you this is to demonstrate how little is actually necessary for the functioning of The Loop. The bulk of the stuff in your ttindex.php/tt is CSS, HTML, and PHP declarations to make The Loop look pretty. pre lt;?php get_header(); if (have_posts()) :

  while (have_posts()) :
     the_post();
     the_content();
  endwhile;

endif; get_sidebar(); get_footer(); ?gt; /pre

Now, let's look at the bulk of the stuff that makes The Loop look pretty.

The Default Loop

The following is a step-by-step look at the default usage of the Loop that comes with the default and classic theme in the standard installation of WordPress v1.5.

Begin The Loop

Found at the top of the default ttindex.php/tt template file is the starting code for The Loop. prelt;?php if (have_posts()) : ?gt; ?php while (have_posts()) : the_post(); ?/pre

  1. First it checks whether any posts were collected with the tthave_posts()/tt function.
  2. If there are any posts, a PHP ttwhile/tt loop is started. A ttwhile/tt loop will continue to execute as long as the condition in the parenthesis is logically true. So as long as the function tthave_posts()/tt returns a true value, The Loop will keep going.
  3. The function tthave_posts()/tt simply checks the next item in the collection of posts: if there's another item, return true; if there is no next item, return false.

Generating the Post

The function ttthe_post()/tt takes the current item in the collection of posts and makes it available for use inside this iteration of The Loop. Without ttthe_post()/tt, many of the Template Tags used in your theme would not work.

Once the post data is made available, the template can start showing post data to the visitor.

Title, Date and Author

The following template tags get the current post's title, as well as the time it was posted and who posted it. pre lt;h2 id=post-lt;?php the_ID(); ?gt;gt; lt;a href=lt;?php the_permalink() ? rel=bookmark title=Permanent Link to lt;?php the_title(); ?gt;gt; lt;?php the_title(); ?gt;lt;/agt;lt;/h2gt; lt;smallgt;lt;?php the_time('F jS, Y') ?gt; lt;!-- by lt;?php the_author() ?gt; --gt;lt;/smallgt; /pre

Post Content

The ttthe_content()/tt template tag displays the content of the post. This is the meat and potatoes of each pass through The Loop: pre lt;div class=entrygt; lt;?php the_content('Read the rest of this entry amp;raquo;'); ?gt; lt;/divgt; /pre If you include the Quicktag button called more, and shown as ttlt;!--more--gt;/tt, in the body of your post, only the portion emabove/em that line will be displayed to viewers. So, if you only want your front page to show the first sentence or two of every post, simply insert ttlt;!--more--gt;/tt after the first line into every post you make.

When viewing a single post, the ttlt;!--more--gt;/tt delimiter is skipped. So putting the ttlt;!--more--gt;/tt delimiter into all your posts forces readers to click through to each individual post if they want to read the whole thing.

Additional Details

Beneath each post's content in the ttindex.php/tt template file is a place to display more information about the post, such as the categories, date, and comment information. Known as the post meta data section, if you're a logged in user of sufficient privilege (or the post's author), you will also see an Edit This link, thanks to the ttedit_post_link()/tt template tag function. pre lt;p class=postmetadatagt; Posted in lt;?php the_category(', ') ?gt; lt;stronggt;|lt;/stronggt; lt;?php edit_post_link('Edit',,'strong|/strong'); ?gt; lt;?php comments_popup_link('No Comments #187;', '1 Comment #187;', '% Comments #187;'); ?gt;lt;/pgt; /pre

If commenting is enabled, or if the post has comments, the ttcomments_popup_link()/tt template tag will display a link to the comments. If you're using the comments popup window, this link will open the comments window; otherwise it will jump right to this post's comments.

If the visitor is viewing an index of posts (i.e.: more than one post in The Loop), the ttcomments_popup_link()/tt link will take the reader to this post's individual page.

Trackback Autodiscovery

The tttrackback_rdf/tt template tag's function is to output machine-readable code used for trackback auto-discovery.

pre lt;!-- lt;?php trackback_rdf(); ?gt; --gt; /pre

Note: The tttrackback_rdf()/tt tag is supposed to be used with comments around it. It is not turned off.

Ending The Loop

The following ends The Loop. After this, the various post-related template tags will not work as expected (or if they do, they will use the last post from The Loop). This means, that if you need to use a template tag that works within The Loop, you need to put it in before this point. pre lt;?php endwhile; ?gt; /pre

This section, immediately after the end of The Loop, displays navigation controls to move forward and backward by each web page. pre lt;div class=navigationgt; lt;div class=alignleftgt;lt;?php posts_nav_link(,,'amp;laquo; Previous Entries') ?gt;lt;/divgt; lt;div class=alignrightgt;lt;?php posts_nav_link(,'Next Entries amp;raquo;',) ?gt;lt;/divgt; lt;/divgt; /pre

If the blog is set to display 10 posts per page, and the conditions used by The Loop collect 25 posts, there will be three pages to navigate: two pages of 10 posts each, and one page of 5 posts. The navigation links will allow the visitor to move forward and backward through the collection of posts.

The navigation controls are included emoutside/em The Loop, but eminside/em the ttif/tt condition, so that they only show up if there are any posts. The navigation functions themselves also check whether or not there is anything to which they will link, based on the current Loop, and only display links if there's something to link.

pre lt;?php else : ?gt;

lt;h2 class=centergt;Not Foundlt;/h2gt;
lt;p class=centergt;

lt;?php _e(Sorry, but you are looking for something that isn't here.); ?gt;lt;/pgt; /pre The ttelse :/tt clause determines what to do if tthave_posts()/tt (from way up at the top) is false. That is to say, the stuff after the else will only be executed/displayed if The Loop had zero posts. No posts show up if, for example, the visitor requested a specific day for which no posts were made or a search was performed that produced no results.

pre

 lt;?php endif; ?gt;

/pre This ends the conditional test of if there are posts do this, else if there are no posts, do that. Once the conditional test is finished, the default index.php template next includes the sidebar, and finally the footer.

The Loop In Other Templates

WordPress can use different template files for displaying your blog in different ways. In the default WordPress theme, there are template files for the index view, category view, and archive view, as well as a template for viewing individual posts. Each of these uses The Loop, but does so with slightly different formatting, as well as different uses of the template tags.

For any view which does not have a separate template file, WordPress will use ttindex.php/tt by default. If a visitor requests a single post, WordPress will first look for a file named ttsingle.php/tt. If that file exists, it will be used to present the post to the visitor. If that file does not exist, WordPress will use ttindex.php/tt to present the post to the visitor. This is called the Template Hierarchy.

If you are making your own Theme, it's often helpful to look at the template files from the default Theme as a point of reference. It's also helpful to use your theme's ttindex.php/tt as a template for your other template files. Doing so may give you a known and working page from which to begin making changes as you create more template files.

Different Archive Format

An emarchive/em is a collection of historical posts. In the default usage, the posts displayed on your main index are recent chronological postings. When a visitor clicks on one of your archive links, or if they manually request a specific date (nowikihttp://www.example.com/blog/index.php?m=200504/nowiki or nowikihttp://www.example.com/blog/2005/04/nowiki to select all posts from April, 2005), WordPress will display an emarchive/em view. By default, the archive will use ttindex.php/tt, and thus look the same as your front page, just displaying the posts from April 2005.

When WordPress prepares an archive view for a visitor, it specifically looks for a file named ttarchive.php/tt in your current theme's directory. If you'd like to visually disambiguate archives from your front page, simply copy ttindex.php/tt to ttarchive.php/tt, and edit ttarchive.php/tt as necessary!

For example, if you want to show only post titles, and no post content, for your list of archives, you could use something like this: pre lt;?php get_header(); ?gt;

lt;div id=content class=narrowcolumngt;
 lt;?php if (have_posts()) : ?gt;
  lt;?php while (have_posts()) : the_post(); ?gt;
    lt;div class=postgt;
    lt;h2 id=post-lt;?php the_ID(); ?gt;gt;

lt;a href=lt;?php the_permalink() ?gt; rel=bookmark title=Permanent Link to lt;?php the_title(); ?gt;gt;lt;?php the_title(); ?gt;lt;/agt;lt;/h2gt;

    lt;smallgt;lt;?php the_time('F jS, Y') ?gt; lt;!-- by lt;?php the_author() ?gt; --gt;lt;/smallgt;
     lt;/divgt;
   lt;?php endwhile; ?gt;

lt;div class=navigationgt; lt;div class=alignleftgt; lt;?php posts_nav_link(,,'amp;laquo; Previous Entries') ?gt; lt;/divgt; lt;div class=alignrightgt; lt;?php posts_nav_link(,'Next Entries amp;raquo;',) ?gt; lt;/divgt;

 lt;/divgt;

lt;?php else : ?gt;

 lt;h2 class=centergt;Not Foundlt;/h2gt;
lt;p class=centergt;lt;?php _e(Sorry, but you are looking for something that isn't here.); ?gt;lt;/pgt;
 lt;?php endif; ?gt;

lt;/divgt; lt;?php get_sidebar(); ?gt; lt;?php get_footer(); ?gt; /pre

Different Category Format

Like the archive views, WordPress looks for a separate template file for category views. If a visitor clicks on a link for a category in your blog, they will be taken to the category view. WordPress will prepare The Loop with posts from that category only, limiting the number of posts per the blog's default settings.

To make your category view different from your index view, copy ttindex.php/tt and rename it ttcategory.php/tt. For a category view, it's probably not necessary to list the categories to which a post is assigned, so let's remove that portion. Instead, let's announce the category at the top of the page: pre lt;?php get_header(); ?gt;

lt;div id=content class=narrowcolumngt;
lt;pgt;
lt;stronggt;
 lt;?php single_cat_title('Currently browsing '); ?gt;
 lt;/stronggt;lt;br /gt;
lt;?php echo category_description(); ?gt;
lt;/pgt;
lt;?php if (have_posts()) : ?gt;
  lt;?php while (have_posts()) : the_post(); ?gt;
    lt;div class=postgt;
     lt;h2 id=post-lt;?php the_ID(); ?gt;gt;

lt;a href=lt;?php the_permalink() ?gt; rel=bookmark title=Permanent Link to lt;?php the_title(); ?gt;gt; lt;?php the_title(); ?gt;lt;/agt;lt;/h2gt;

  lt;smallgt;
    lt;?php the_time('F jS, Y') ?gt; 
       lt;!-- by lt;?php the_author() ?gt; --gt;
  lt;/smallgt;
lt;/divgt;

lt;?php endwhile; ?gt;

lt;div class=navigationgt;
  lt;div class=alignleftgt;
   lt;?php posts_nav_link(,,'amp;laquo; Previous Entries') ?gt;
  lt;/divgt;
  lt;div class=alignrightgt;
   lt;?php posts_nav_link(,'Next Entries amp;raquo;',) ?gt;
  lt;/divgt;
lt;/divgt;

lt;?php else : ?gt;

 lt;h2 class=centergt;Not Foundlt;/h2gt;

lt;p class=centergt;lt;?php _e(Sorry, but you are looking for something that isn't here.); ?gt;lt;/pgt;

lt;?php endif; ?gt;

lt;/divgt; lt;?php get_sidebar(); ?gt; lt;?php get_footer(); ?gt; /pre

Different Formats for Different Categories

As explained in the Template Hierarchy, it is possible to create separate template files for each category. Simply name the file ttcategory-buX/u/b.php/tt, where buX/u/b is the numerical ID of the category. Consider carefully whether you need a whole new template for a specific category.

Let's look at two categories, Plants and Flowers, with category IDs 3 and 4, respectively. Next to each post title in the output you want to have picture of either a plant, or a flower, depending on which category is being displayed. You could:

  • Use two separate files, ttcategory-3.php/tt and ttcategory-4.php/tt, each with a different ttimg/tt tag for each post title.
  • Use a conditional test inside your default ttcategory.php/tt file to check whether the current category is Plants or Flowers (or neither), and display the appropriate image:

pre lt;?php if (is_category('3') ):

// we're in the Plants category, so show a plant ?gt;
lt;img src='/images/plant.png' alt='a plant' /gt;

lt;?php } elseif (is_category('4') ):

// we're in the Flowers category, so show a flower ?gt;
lt;img src='/images/flower.png' alt='a pretty flower' /gt;

lt;?php endif; // end the if, no images for other other categories ?gt; /pre

If you added another category, Cars, which you wanted to display in a emsignificantly/em different way, then a separate ttcategory-buX/u/b.php/tt would be more appropriate.

Different CSS For Different Categories

Many users want to create separate CSS files for a specific category. This, too, can be easily accomplished. It is important to remember that stylesheets are defined and loaded in the ttlt;headgt;/tt section of the HTML document. WordPress uses the ttheader.php/tt file for this. In the default ttheader.php/tt, find this line: pre lt;link rel=stylesheet href=lt;?php bloginfo('stylesheet_url'); ?gt; type=text/css media=screen /gt; /pre And change it to something like this: pre lt;?php if ( is_category('5') ) { // Load special CSS for Cars category ?gt;

 link rel=stylesheet href=?php bloginfo('template_url'); ?/category-5.css type=text/css media=screen /;

lt;?php } else { ?gt;

  link rel=stylesheet href=?php bloginfo('stylesheet_url'); ? type=text/css media=screen /

lt;?php } ?gt; /pre strongNote:/strong The Cars template uses the ttcategory-5.css/tt file to override the default layout. In this example the CSS file is named after the category template file to which it will be applied, rather than the actual name of the category. Thus, you know that ttcategory-5.css/tt goes with ttcategory-5.php/tt.

Different Single Post Format

When viewing any single post (or permalink), WordPress will use ttsingle.php/tt, if present.

This portion, from the WordPress default single.php, provides the post meta data information about the current post: pre p class=postmetadata alt small This entry was posted on lt;?php the_time('l, F jS, Y') ?gt; at lt;?php the_time() ?gt; and is filed under lt;?php the_category(', ') ?gt;. You can follow any responses to this entry through the lt;?php comments_rss_link('RSS 2.0'); ?gt; feed. lt;?php if (('open' == $post-gt;comment_status) ('open' == $post-ping_status)) { // Both Comments and Pings are open ?gt;

 You can lt;a href=#respondgt;leave a responselt;/agt;, or 
 lt;a href=lt;?php trackback_url(display); ?gt;gt;trackbacklt;/agt; 

from your own site. lt;?php } elseif (!('open' == $post-gt;comment_status) ('open' == $post-ping_status)) { // Only Pings are Open ?gt;

 Responses are currently closed, but you can 
 lt;a href=lt;?php trackback_url(display); ?gt; gt;trackbacklt;/agt; 

from your own site. lt;?php } elseif (('open' == $post-gt;comment_status)  !('open' == $post-ping_status)) { // Comments are open, Pings are not ?gt;

 You can skip to the end and leave a response. Pinging is currently not allowed.

lt;?php } elseif (!('open' == $post-gt;comment_status)  !('open' == $post-ping_status)) { // Neither Comments, nor Pings are open ?gt;

 Both comments and pings are currently closed.

lt;?php } edit_post_link('Edit this entry.',,); ?gt; lt;/smallgt; lt;/pgt; /pre This sort of information -- whether comments are open or closed -- is largely inappropriate on an index, archive, or category view; which is why it's only included in the ttsingle.php/tt template file.

Other Loop Tricks

Now that you have a good introduction to the basic uses for the WordPress Loop, let's introduce you to some more Loop effects and tricks.

Static Front Page

How can you display something special emonly/em on the front page of your blog? That's right, only on the front page or home page, and have it not be seen anywhere else on your site. Easy! We call this the static front page. The front or first page of your site isn't really static. It's just using the Loop to make it look that way.

To make this Loop trick work, use the ttis_home()/tt conditional template tag function.

In your ttindex.php/tt, use an ttif ()/tt test to conditionally output additional content:

pre lt;?php get_header(); ?gt; lt;?php if (is_home()) {

// we're on the home page, so let's show a picture of our new kitten!
echo lt;img src='/images/new_kitty.jpg' alt='Our new cat, Rufus!' /gt;;
// and now back to our regularly scheduled home page

} ?gt; /pre

The function ttis_home()/tt will only produce a true value if the visitor is not requesting a specific post, page, category, or date, so it only shows up on the home page.

For more information, see Creating a Static Front Page.

Excerpts Only

The easiest way to display excerpts, instead of the full content, of posts, replace all instances of ttthe_content()/tt with ttthe_excerpt()/tt. If you have not created explicit excerpts for your posts, this function will automatically display the first 55 words of the post. pre lt;div class=entrygt; lt;?php the_excerpt(); ?gt; lt;/divgt; /pre

Showing Excerpts or Full Post Depending Upon Number of Posts

In some circumstances, for example on archive pages, you may want to show the full post if there is only one post or excerpts if there are multiple posts. You can customize the loop to do this.

pre ?php if (have_posts()) : ?

 ?php if (($wp_query-post_count)  1) : ?
    ?php while (have_posts()) : the_post(); ?
      !-- Do your post header stuff here for excerpts--
         ?php the_excerpt() ?
      !-- Do your post footer stuff here for excerpts--
    ?php endwhile; ?
 ?php else : ?
    ?php while (have_posts()) : the_post(); ?
      !-- Do your post header stuff here for single post--
         ?php the_content() ?
      !-- Do your post footer stuff here for single post--
    ?php endwhile; ?
 ?php endif; ?

?php else : ?

    !-- Stuff to do if there are no posts--

?php endif; ?

/pre

Different Headers/Sidebars/Footers

WordPress offers the ttget_header()/tt, ttget_sidebar()/tt, and ttget_footer()/tt Include Tags for use in your template files. These functions make it easy to define a standard header/sidebar/footer which is easily editable. Any changes made to these files will immediately be made visible to viewers, without any work on your part.

But sometimes you might not emwant/em a sidebar. If you don't want a sidebar, simply exclude the call to the ttget_sidebar()/tt function from your template. For example, the ttsingle.php/tt template in the WordPress default theme does not include a sidebar.

To create your own strongdifferent/strong sidebar, you have two choices:

  1. Include the sidebar contents directly into the template file on which you're working. If you want category-3 to have a different sidebar, edit ttcategory-3.php/tt and include the necessary HTML and PHP to generate your distinctive sidebar.
  2. Use the PHP ttinclude/tt function, to include another file. The WordPress ttget_sidebar()/tt function emonly/em loads ttsidebar.php/tt. If you make a file named ttsideleft.php/tt, you would include it like this:

pre lt;?php include(TEMPLATEPATH . '/sideleft.php'); ?gt; /pre

In Wordpress Version 2.5 and above you can also call a sidebar like this: pre lt;?php get_sidebar('right'); ?gt; /pre

This causes the template TEMPLATEPATH . 'sidebar-right.php' to be included.

Using the WordPress default Template Hierarchy, if you want to use the same elements on multiple or different templates, it's probably best to put them in separate template files and use the PHP ttinclude()/tt function. If the element you're adding is specifically for one template file, it's probably best to include it directly in that template file.

Summary

We've just scratched the surface of what can be done with the Loop. As a reminder, the following are resources that will help you customize your own WordPress Loop.

wordpress