站长百科 | 数字化技能提升教程 数字化时代生存宝典
首页
数字化百科
电子书
▼
建站程序
开发
服务器
办公软件
开发教程
▼
服务器教程
软件使用教程
运营教程
热门电子书
▼
CSS教程
WordPress教程
导航
程序频道
推广频道
网赚频道
人物频道
网站程序
网页制作
云计算
服务器
CMS
论坛
网店
虚拟主机
cPanel
网址导航
WIKI使用导航
WIKI首页
热点词条
最新资讯
网站程序
站长人物
页面分类
使用帮助
编辑测试
创建条目
网站地图
站长百科导航
站长百科
主机侦探
IDCtalk云说
跨境电商导航
WordPress啦
站长专题
网站推广
网站程序
网站赚钱
虚拟主机
cPanel
网址导航专题
云计算
微博营销
虚拟主机管理系统
开放平台
WIKI程序与应用
美国十大主机
编辑“
WordPress:The Loop in Action
”
人物百科
|
营销百科
|
网赚百科
|
站长工具
|
网站程序
|
域名主机
|
互联网公司
|
分类索引
Xxf3325
(
讨论
|
贡献
)
2008年4月10日 (四) 09:45的版本
(新页面: ==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 t...)
(差异) ←上一版本 |
最后版本
(
差异
) |
下一版本→
(
差异
)
跳转至:
导航
、
搜索
警告:您正在编辑的是本页面的旧版本。
如果您发布该更改,该版本后的所有更改都会丢失。
警告:
您没有登录。如果您做出任意编辑,您的IP地址将会公开可见。如果您
登录
或
创建
一个账户,您的编辑将归属于您的用户名,且将享受其他好处。
反垃圾检查。
不要
加入这个!
==Introduction== [[WordPress:The Loop|"The Loop"]] is a term that refers to the main process of WordPress. You use The Loop in your [[WordPress:Templates|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 [[WordPress:Registered_User_Features|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 [[WordPress:Administration_Panels|Administration]] > [[WordPress:Administration_Panels#Reading|Settings]] > [[WordPress:Settings_Reading_SubPanel|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 <tt>index.php</tt> to display everything. For the first part of this discussion of The Loop we'll focus only on <tt>index.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 <tt>index.php</tt> is CSS, HTML, and PHP declarations to make The Loop look pretty. <pre> <?php get_header(); if (have_posts()) : while (have_posts()) : the_post(); the_content(); endwhile; endif; get_sidebar(); get_footer(); ?> </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 <tt>index.php</tt> template file is the starting code for [[WordPress:The Loop]]. <pre><?php if (have_posts()) : ?><br /> <?php while (have_posts()) : the_post(); ?></pre> #First it checks whether any posts were collected with the <tt>have_posts()</tt> function. #If there are any posts, a PHP <tt>[http://www.php.net/while while]</tt> loop is started. A <tt>while</tt> loop will continue to execute as long as the condition in the parenthesis is logically true. So as long as the function <tt>have_posts()</tt> returns a true value, The Loop will keep going. #The function <tt>have_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 <tt>the_post()</tt> takes the current item in the collection of posts and makes it available for use inside this iteration of The Loop. Without <tt>the_post()</tt>, many of the [[WordPress: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 [[WordPress:Template Tags|template tags]] get the current post's title, as well as the time it was posted and who posted it. <pre> <h2 id="post-<?php the_ID(); ?>"> <a href="<?php the_permalink() ?>" rel="bookmark" title="Permanent Link to <?php the_title(); ?>"> <?php the_title(); ?></a></h2> <small><?php the_time('F jS, Y') ?> <!-- by <?php the_author() ?> --></small> </pre> ====Post Content==== The <tt>[[WordPress:Template_Tags/the_content|the_content()]]</tt> template tag displays the content of the post. This is the meat and potatoes of each pass through The Loop: <pre> <div class="entry"> <?php the_content('Read the rest of this entry &raquo;'); ?> </div> </pre> If you include the [[WordPress:Write_Post_SubPanel#Quicktags|Quicktag]] button called '''more''', and shown as <tt>[[WordPress:Customizing_the_Read_More|<!--more-->]]</tt>, in the body of your post, only the portion <em>above</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 <tt><!--more--></tt> after the first line into every post you make. When viewing a single post, the <tt><!-- more --></tt> delimiter is skipped. So putting the <tt><!-- more --></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 <tt>index.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 [[WordPress:Post_Meta_Data_Section|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 <tt>[[WordPress:Template_Tags/edit_post_link|edit_post_link()]]</tt> template tag function. <pre> <p class="postmetadata"> Posted in <?php the_category(', ') ?> <strong>|</strong> <?php edit_post_link('Edit','','<strong>|</strong>'); ?> <?php comments_popup_link('No Comments »', '1 Comment »', '% Comments »'); ?></p> </pre> If commenting is enabled, or if the post has comments, the <tt>[[WordPress:Template_Tags/comments_popup_link|comments_popup_link()]]</tt> template tag will display a link to the comments. If you're using the [[WordPress:Template_Tags/comments_popup_script|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 <tt>comments_popup_link()</tt> link will take the reader to this post's individual page. ====Trackback Autodiscovery==== The <tt>[[WordPress:Template_Tags/trackback_rdf|trackback_rdf]]</tt> template tag's function is to output machine-readable code used for [[WordPress:Glossary#Trackback|trackback]] auto-discovery. <pre> <!-- <?php trackback_rdf(); ?> --> </pre> '''Note:''' The <tt>trackback_rdf()</tt> tag is supposed to be used with [[WordPress:Commenting_Code|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> <?php endwhile; ?> </pre> This section, immediately after the end of The Loop, displays navigation controls to move forward and backward by each web page. <pre> <div class="navigation"> <div class="alignleft"><?php posts_nav_link('','','&laquo; Previous Entries') ?></div> <div class="alignright"><?php posts_nav_link('','Next Entries &raquo;','') ?></div> </div> </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 <em>outside</em> The Loop, but <em>inside</em> the <tt>if</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> <?php else : ?> <h2 class="center">Not Found</h2> <p class="center"> <?php _e("Sorry, but you are looking for something that isn't here."); ?></p> </pre> The <tt>else :</tt> clause determines what to do if <tt>have_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> <?php endif; ?> </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 [[WordPress:Templates|template files]] for the index view, category view, and archive view, as well as a template for viewing individual posts. Each of these uses [[WordPress:The Loop]], but does so with slightly different formatting, as well as different uses of the [[WordPress:Template_Tags|template tags]]. For any view which does not have a separate template file, WordPress will use <tt>index.php</tt> by default. If a visitor requests a single post, WordPress will first look for a file named <tt>single.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 <tt>index.php</tt> to present the post to the visitor. This is called the [[WordPress:Template Hierarchy]]. If you are making your own [[WordPress:Using Themes|Theme]], it's often helpful to look at the [[WordPress:Templates|template files]] from the default Theme as a point of reference. It's also helpful to use your theme's <tt>index.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 <em>archive</em> is a collection of historical posts. In the default usage, the posts displayed on your main index are recent [http://mydatapages.com/chronological.html chronological] postings. When a visitor clicks on one of your archive links, or if they manually request a specific date (<nowiki>http://www.example.com/blog/index.php?m=200504</nowiki> or <nowiki>http://www.example.com/blog/2005/04</nowiki> to select all posts from April, 2005), WordPress will display an <em>archive</em> view. By default, the archive will use <tt>index.php</tt>, and thus look the same as your front page, just displaying the posts from April 2005. When WordPress prepares an [[WordPress:Creating_an_Archive_Index|archive view]] for a visitor, it specifically looks for a file named <tt>archive.php</tt> in your current theme's directory. If you'd like to visually disambiguate archives from your front page, simply copy <tt>index.php</tt> to <tt>archive.php</tt>, and edit <tt>archive.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> <?php get_header(); ?> <div id="content" class="narrowcolumn"> <?php if (have_posts()) : ?> <?php while (have_posts()) : the_post(); ?> <div class="post"> <h2 id="post-<?php the_ID(); ?>"> <a href="<?php the_permalink() ?>" rel="bookmark" title="Permanent Link to <?php the_title(); ?>"><?php the_title(); ?></a></h2> <small><?php the_time('F jS, Y') ?> <!-- by <?php the_author() ?> --></small> </div> <?php endwhile; ?> <div class="navigation"> <div class="alignleft"> <?php posts_nav_link('','','&laquo; Previous Entries') ?> </div> <div class="alignright"> <?php posts_nav_link('','Next Entries &raquo;','') ?> </div> </div> <?php else : ?> <h2 class="center">Not Found</h2> <p class="center"><?php _e("Sorry, but you are looking for something that isn't here."); ?></p> <?php endif; ?> </div> <?php get_sidebar(); ?> <?php get_footer(); ?> </pre> ===Different Category Format=== Like the archive views, WordPress looks for a separate template file for [[WordPress:Category_Templates|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 <tt>index.php</tt> and rename it <tt>category.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> <?php get_header(); ?> <div id="content" class="narrowcolumn"> <p> <strong> <?php single_cat_title('Currently browsing '); ?> </strong><br /> <?php echo category_description(); ?> </p> <?php if (have_posts()) : ?> <?php while (have_posts()) : the_post(); ?> <div class="post"> <h2 id="post-<?php the_ID(); ?>"> <a href="<?php the_permalink() ?>" rel="bookmark" title="Permanent Link to <?php the_title(); ?>"> <?php the_title(); ?></a></h2> <small> <?php the_time('F jS, Y') ?> <!-- by <?php the_author() ?> --> </small> </div> <?php endwhile; ?> <div class="navigation"> <div class="alignleft"> <?php posts_nav_link('','','&laquo; Previous Entries') ?> </div> <div class="alignright"> <?php posts_nav_link('','Next Entries &raquo;','') ?> </div> </div> <?php else : ?> <h2 class="center">Not Found</h2> <p class="center"><?php _e("Sorry, but you are looking for something that isn't here."); ?></p> <?php endif; ?> </div> <?php get_sidebar(); ?> <?php get_footer(); ?> </pre> ===Different Formats for Different Categories=== As explained in the [[WordPress:Template Hierarchy]], it is possible to [[WordPress:Category_Templates|create separate template files for each category]]. Simply name the file <tt>category-<b><u>X</u></b>.php</tt>, where <b><u>X</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, <tt>category-3.php</tt> and <tt>category-4.php</tt>, each with a different <tt>img</tt> tag for each post title. * Use a conditional test inside your default <tt>category.php</tt> file to check whether the current category is "Plants" or "Flowers" (or neither), and display the appropriate image: <pre> <?php if (is_category('3') ): // we're in the Plants category, so show a plant ?> <img src='/images/plant.png' alt='a plant' /> <?php } elseif (is_category('4') ): // we're in the Flowers category, so show a flower ?> <img src='/images/flower.png' alt='a pretty flower' /> <?php endif; // end the if, no images for other other categories ?> </pre> If you added another category, "Cars", which you wanted to display in a <em>significantly</em> different way, then a separate <tt>category-<b><u>X</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 <tt><head></tt> section of the HTML document. WordPress uses the <tt>header.php</tt> file for this. In the default <tt>header.php</tt>, find this line: <pre> <link rel="stylesheet" href="<?php bloginfo('stylesheet_url'); ?>" type="text/css" media="screen" /> </pre> And change it to something like this: <pre> <?php if ( is_category('5') ) { // Load special CSS for "Cars" category ?> <link rel="stylesheet" href="<?php bloginfo('template_url'); ?>/category-5.css" type="text/css" media="screen" />; <?php } else { ?> <link rel="stylesheet" href="<?php bloginfo('stylesheet_url'); ?>" type="text/css" media="screen" /> <?php } ?> </pre> <strong>Note:</strong> The Cars template uses the <tt>category-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 <tt>category-5.css</tt> goes with <tt>category-5.php</tt>. ===Different Single Post Format=== When viewing any single post (or [[WordPress:Glossary#Permalink|permalink]]), WordPress will use <tt>single.php</tt>, if present. This portion, from the WordPress default single.php, provides the [[WordPress:Post_Meta_Data_Section|post meta data information]] about the current post: <pre> <p class="postmetadata alt"> <small> This entry was posted on <?php the_time('l, F jS, Y') ?> at <?php the_time() ?> and is filed under <?php the_category(', ') ?>. You can follow any responses to this entry through the <?php comments_rss_link('RSS 2.0'); ?> feed. <?php if (('open' == $post->comment_status) && ('open' == $post->ping_status)) { // Both Comments and Pings are open ?> You can <a href="#respond">leave a response</a>, or <a href="<?php trackback_url(display); ?>">trackback</a> from your own site. <?php } elseif (!('open' == $post->comment_status) && ('open' == $post->ping_status)) { // Only Pings are Open ?> Responses are currently closed, but you can <a href="<?php trackback_url(display); ?> ">trackback</a> from your own site. <?php } elseif (('open' == $post->comment_status) && !('open' == $post->ping_status)) { // Comments are open, Pings are not ?> You can skip to the end and leave a response. Pinging is currently not allowed. <?php } elseif (!('open' == $post->comment_status) && !('open' == $post->ping_status)) { // Neither Comments, nor Pings are open ?> Both comments and pings are currently closed. <?php } edit_post_link('Edit this entry.','',''); ?> </small> </p> </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 <tt>single.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 <em>only</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 [[WordPress:Conditional_Tags#The_Main_Page|is_home()]] conditional template tag function. In your <tt>index.php</tt>, use an <tt>if ()</tt> test to conditionally output additional content: <pre> <?php get_header(); ?> <?php if (is_home()) { // we're on the home page, so let's show a picture of our new kitten! echo "<img src='/images/new_kitty.jpg' alt='Our new cat, Rufus!' />"; // and now back to our regularly scheduled home page } ?> </pre> The function <tt>is_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 [[WordPress:Creating a Static Front Page]]. ===Excerpts Only=== The easiest way to display excerpts, instead of the full content, of posts, replace all instances of <tt>[[WordPress:Template_Tags/the_content|the_content]]()</tt> with <tt>[[WordPress:Template_Tags/the_excerpt|the_excerpt()]]</tt>. If you have not created explicit excerpts for your posts, this function will automatically display the first 120 words of the post. <pre> <div class="entry"> <?php the_excerpt(); ?> </div> </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 <tt>get_header()</tt>, <tt>get_sidebar()</tt>, and <tt>get_footer()</tt> [[WordPress:Include Tags]] for use in your [[WordPress:Templates|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 <em>want</em> a sidebar. If you don't want a sidebar, simply exclude the call to the <tt>get_sidebar()</tt> function from your template. For example, the <tt>single.php</tt> template in the WordPress default theme does not include a sidebar. To create your own <strong>different</strong> sidebar, you have two choices. # 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 <tt>category-3.php</tt> and include the necessary HTML and PHP to generate your distinctive sidebar. # Use the PHP <tt>[http://www.php.net/include include]</tt> function, to include another file. The WordPress <tt>get_sidebar()</tt> function <em>only</em> loads <tt>sidebar.php</tt>. If you make a file named <tt>sideleft.php</tt>, you would include it like this: <pre> <?php include(TEMPLATEPATH . '/sideleft.php'); ?> </pre> Using the WordPress default [[WordPress: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 <tt>include()</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:The Loop|WordPress Loop]]. * [[WordPress:Templates|Template Files]] * [[WordPress:Template Tags]] * [[WordPress:Template Hierarchy]] * [[WordPress:Conditional Tags]] ==Resources== * [http://www.obeattie.com/2006/05/02/wordpress-the-loop/ oBeattie : The Loop] * [http://www.themelab.com/2008/04/04/the-ultimate-guide-to-the-wordpress-loop/ The Ultimate Guide to the WordPress Loop]
摘要:
请注意,您对站长百科的所有贡献都可能被其他贡献者编辑,修改或删除。如果您不希望您的文字被任意修改和再散布,请不要提交。
您同时也要向我们保证您所提交的内容是您自己所作,或得自一个不受版权保护或相似自由的来源(参阅
Wordpress-mediawiki:版权
的细节)。
未经许可,请勿提交受版权保护的作品!
取消
编辑帮助
(在新窗口中打开)
本页使用的模板:
模板:WordPress导航
(
查看源代码
)(受保护)