WordPress模板層次03:模板檔案中常見程式碼

huangbangqing12發表於2018-07-08

在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檔案。並開啟它。

通過檢視 content-page.php 檔案,你應該能夠猜出:這個檔案才是構建頁面主要內容的檔案。

相關文章