天天看點

WordPress模闆層次03:模闆檔案中常見代碼

在WordPress模闆檔案中常見的代碼,首先要說的是​​循環​​。

循環通常以 while 語句開頭:

<?php 
if ( have_posts() ) {
    while ( have_posts() ) {/***循環以while語句開始***/
        the_post(); 
        //
        // Post Content here
        //
    } // end while
} // end if
?>      

WP Query

循環通常和 ​​WP_Query​​ 一起使用:可以循環周遊給定頁面的所有内容。

你可以參考之前的一篇文章: ​​WordPress開發入門07:WP_Query 自定義循環​​

WP Query是一個可以添加到循環中的,可定制化搜尋更具體的内容的函數。例如,WP Query具有所有以下參數。它可以讓我們通過作者,類别,标簽,分類,文章或頁面,訂單,日期查詢來對循環進行限制。

You must be ​​logged in​​ to view the hidden contents.

是以,比如說,如果你想通過作者名找到他所寫的文章。我們可以添加具有作者姓名參數的WP Query,來搜尋那個特定的作者的文章。

$query = new WP_Query( 'author_name=rami' );      

這就是wp_query的作用。

get_template_part

接下來要提到的最後一個重要的函數是 get_template_part 。這個函數在WordPress中的作用是包含檔案。

在WordPress中,通常我們不使用 PHP 的 include 關鍵字,而是使用 ​​get_template_part​​ :

get_template_part接受兩個參數。一個是您要查找的檔案的主要名稱。然後,第二個參數是可選的,它定義了該檔案附加的名稱。

get_template_part( string $slug, string $name = null )      

用法如下:

<?php get_template_part( 'loop', 'index' ); ?>      

它将查找名為 loop-index.php 的檔案。如果沒有,它會按照這個優先級,在文檔目錄中查找對應的檔案。:

wp-content/themes/twentytenchild/loop-index.php
wp-content/themes/twentyten/loop-index.php
wp-content/themes/twentytenchild/loop.php
wp-content/themes/twentyten/loop.php      

常見代碼在模闆檔案中的應用

來看一個示例模闆,看看其中的一些操作。打開主題下的page.php:

You must be ​​logged in​​ to view the hidden contents.

<?php
                // Start the Loop.
                while ( have_posts() ) : the_post();/***while循環***/

                    // Include the page content template.
                    get_template_part( 'content', 'page' );/***get_template_part函數***/

                    // If comments are open or we have at least one comment, load up the comment template.
                    if ( comments_open() || get_comments_number() ) {
                        comments_template();
                    }
                endwhile;/***循環在這裡結束***/
            ?>      

這裡的get_template_part在包含 content-page.php 檔案,是以,在主題目錄下,找到content-page.php檔案。并打開它。

WordPress模闆層次03:模闆檔案中常見代碼