WordPress Theme Development Tutorial Manual - Template Loop

Loop is WordPress through the themeTemplate filesThe default mechanism for outputting posts . In a loop, WordPress iterates over all the posts fetched by the current page, then formats and outputs them using the template tags in the theme.

We can do a lot of things with WordPress loops, for example:

  • Display multiple article modules on the home page of your website
  • Show content and comments on article detail page
  • Show latest posts or popular posts in the sidebar
  • Displays data from a specified article type or taxonomy.
  • Get data according to the specified conditions and display it in the article module

Loop details

The basic use of loops is as follows.

endwhile; endif; ?

The above code first determines whether there is a loop, and if so, displays the contents of the loop one by one.

  • have_posts() function checks if there is an article on the current page. 
  • As long as the conditional logic in the parentheses is true, the while The loop will then continue to execute. 

Using the Article Loop

The loop should be placed in the index.phpor in other templates used to display articles. Since we don't want to display the site header in every article, the loop code should be placed in the get_header() After.

endwhile; endif; ?

As shown in the code above, the loop must begin with if respond in singing while The statement begins with endwhile respond in singing endif End statement. The template tag used to display the content of the article must be in the middle of the loop start statement and end statement.

If there are no articles on the current page, we can display a 404 error message, which must be placed in the endwhile respond in singing endif between statements , as shown below.

It's a very simple index.php Article.

endif; get_sidebar(); get_footer(); ?

What can be displayed in the article loop

We can use template tags in the loop to display a variety of article content, article custom fields, the following are some commonly used template tags:

When displaying an article, we can use conditional tags to control whether the article is displayed if certain conditions are met.

typical example

Let's see some real examples of WordPress loops in use.

basic example

Article Listings Page

Most websites have an article list page, in which we can display the title, thumbnail, summary, category and other information of all the articles in this list. The following example is a simple list page, the sample code first checks if there is an article, if so, displays the article title, thumbnail, and summary, if not, then displays a reminder message.

<?php 
if ( have_posts() ) : 
    while ( have_posts() ) : the_post(); 
        the_title( '<h2>', '</h2>' ); 
        the_post_thumbnail(); 
        the_excerpt();
    endwhile; 
else: 
    _e( '抱歉,未找到您需要的文章。', 'textdomain' ); 
endif; 
?>

Article detail page

In WordPress, each post has its own detail page and we can use the template tag to display various information about the post on this page.

In the following example, the template loops through the title and content of the article, in addition to which we can display information such as the article body, the author of the article, and the time of publication.

<?php 
if ( have_posts() ) : 
    while ( have_posts() ) : the_post(); 
        the_title( '<h1>', '</h1>' ); 
        the_content();
    endwhile; 
else: 
    _e( '抱歉,未找到您需要的文章。', 'textdomain' ); 
endif; 
?>

Display different content and styles for posts in a category

Let's look at the template example, in this example:

  • First, it displays the title, publish time, author, body and category of each article.
  • Then, we use the judgment function in_category() to display different styles for posts with category ID 3. 
<?php
// 开始循环
if ( have_posts() ) : 
    while ( have_posts() ) : the_post();
        // 判断文章是否在分类 3 中,如果是,添加 CSS 类 "post-category-three". 否则,添加 CSS 类 "post".
        if ( in_category( 3 ) ) : ?>
            <div class="post-category-three">
        <?php else : ?>
            <div class="post">
        <?php endif; 

            // 显示文章标题
            the_title( '<h2>', ';</h2>' ); 

            // 显示该文章作者存档的链接
            printf( __( '作者 %s', 'textdomain' ), get_the_author_posts_link() );

            // 显示文章内容
            ?>
            <div class="entry">
                <?php the_content() ?>
             </div>
    
            <?php
            // 显示逗号分隔的文章分类
            _e( '文章分类 ', 'textdomain' ); the_category( ', ' ); 

        // 关闭 div
       ?>
       </div>

    <?php 
    // 结束循环,下面是没有文章时显示的内容
    endwhile; 

else :
    // 如果没有文章,显示提示消息
     _e( '抱歉,未找到您需要的文章。', 'textdomain' );
 
// 结束判断和循环
 endif;
?>

primary cycle

The main loop is a very important concept in WordPress, and before we start learning about multiple loops, we first need to understand what a main loop is.

When we visit the WordPress site, WordPress will set a $wp_query global variable based on the page we visit to create a new post query and loop for us. This variable is the main loop data variable, we can loop this data directly in the page template to output posts.

Take a look at the code below:

if ( have_posts() ) :
    while ( have_posts() ) : the_post() ;
        the_title().
    endwhile.
endif.

To illustrate the main loop, let's rewrite the code slightly.

if ( $wp_query->have_posts() ) :
    while ( $wp_query->have_posts() ) : $wp_query->the_post() ;
        the_title();
    endwhile;
endif;

The two pieces of code are equivalent, and to keep the code simple, WordPress hides the global main loop variable $wp_queryThe

multiple loop

In some cases, we may need to use multiple loops. For example, we may need to display the title of the article in the content list at the top of the page, and then display the content of the article at the bottom of the page. Since we are using the same loop, we simply reset the loop before starting the second loop, using the function rewind_posts() This function can be realized.

utilization rewind_posts() The function restarts the loop

We can use the rewind_post() function to make the loop restart from the first element in the loop, which is useful when we need to loop through the same query on a page.

Here's arewind_posts() Example :

endwhile; ?

New Query and Article Loop

As shown in the above code, it is very easy to loop through the same query two or more times, but very often, this is not what we need. Sometimes we need to display different articles on a page, for example, we need to display all articles on the left side of the page and articles in the category "example-category" on the right side. In this case, we need to create a new article query, and then cycle through the results of this new article query, sample code is as follows:

have_posts() )
    echo '
    '; while ( $secondary_query->have_posts() ) : $secondary_query->the_post() ; the_title( '
  • ', '
  • ' ); endwhile. echo '
'; endif; wp_reset_postdata(); ? >

As shown in the example above, we first display the results from the main loop. Then, using the WP_Query ClassQueries articles in the specified category.

Note that there is another difference between the second loop in the above example and the main loop: the latter calls the wp_reset_postdata() function to reset the post data.

Reset multiple article loops

In the loop, the article data is stored in the $postin a global variable, we need to reset this global variable at the end of the loop, otherwise it can lead to some bugs that are hard to debug. Depending on how the loop is called, there are three functions that can be used to reset the loop.

utilization wp_reset_postdata() Reset article data

When a new custom loop is created with WP_Query or multiple loops are used, reset the post data with wp_reset_postdata(), a function that restores the global variable $post variable to the current post in the main query. This function is the most common function used to reset loops if we follow best practices when doing WordPress development.

It is recommended to use the wp_reset_postdata() function to reset the post data when you have created a new query and loop using the WP_Query class.

The following is the sample code for restoring post data using wp_reset_postdata() after creating a new query and loop using the WP-Query class.

 3 );

// Call WP_Query to create a new post query.
$he_query = new WP_Query( $args );

if ( $the_query->have_posts() ) :
    // Start the loop
    while ( $the_query->have_posts() ) : $the_query->the_post() ;
        the_title().
        the_excerpt();
    // End the loop
    endwhile.
else.
    _e( 'Sorry, the article you need was not found.' , 'textdomain' );
endif.

wp_reset_postdata(); ?
? > 

utilization wp_reset_query() Reset main loop and article data

on account of query_posts() The new loop created by the function is a main loop, and after using this function to create a new query, wenecessarilyutilization wp_reset_query() to restore query and article data. If you use theWP_Query new query, we can use the wp_reset_query() function to restore the post data (since that function already calls the wp_reset_postdata() function), but it's best practice to use the wp_reset_postadata function to restore a new post loop that was created using WP_Query.

on account of query_posts()will create a new main loop to replace the current page's main loop, using this function will bring some side effects, the new loop is, we try to use WP_Query instead of query_posts function.

We offer WordPress Themes and Plugins Custom Development Services

This site has long undertaken WordPress themes, plugins, WooCommerce-based store mall development business. We have 10 years of experience in WordPress development, if you want to Developing Websites with WordPress, please contact WeChat: iwillhappy1314 or email: amos@wpcio.com for inquiries.

发表回复

Your email address will not be published. 必填项已用 * 标注

*