使用WP_Query的基礎知識 + 程式碼示例

使用WP_Query的基礎知識 + 程式碼示例

預設情況下,WordPress會自動將您的文章從最新到最舊排序。儘管訪問者可以使用類別和標籤搜尋特定文章,但他們可能無法找到他們正在尋找的內容。要為每位訪問者整理您的文章,使用WP_Query會很有幫助。

使用WP_Query,您可以自定義網站文章和頁面的顯示。這個PHP類使您能夠簡化複雜的資料庫請求。作為開發人員或網站所有者,它可以幫助您自定義超出預設主題的頁面。

在這篇文章中,我們將解釋什麼是WP_Query。然後,我們將向您展示如何在您的WordPress網站上使用它。最後,我們將為您提供一些在您的部落格上實現它的方法示例。

WP_Query簡介

在WordPress中,您網站的資料儲存在MySQL資料庫中。這包括從文章、頁面和評論到您的配置設定的所有內容。

當訪問者點選您的網站時,會向您的WordPress資料庫傳送一個請求。您的資料庫檢索特定的文章和頁面以根據此查詢顯示它們。

作為網站所有者,您可以利用查詢從資料庫中獲取特定資訊。儘管您可以構建SQL查詢,但這並不是檢索資料的最有效方式。這就是WP_Query的用武之地。

WP_Query是一個PHP類,您可以使用它來為您的資料庫構建查詢。在WordPress中,這是一個內建類,每當有人搜尋您的內容時就會出現。

搜尋文章列表

但是,實施自定義WordPress查詢可以使使用者無需搜尋即可找到特定內容。如果您需要在網站的前端呈現一組特定的文章,您可以使用WP_Query自定義文章型別輕鬆完成此操作。

例如,您可能想要建立一個WordPress自定義文章型別。要顯示這些文章,您可以編寫特定查詢。這是您可以使用的基本程式碼結構

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
// WP QUERY
$query = new WP_Query([
'post_type' => 'press-release'
"posts_per_page => 25,
'category_name' => 'health',
]);
// WP QUERY $query = new WP_Query([ 'post_type' => 'press-release' "posts_per_page => 25, 'category_name' => 'health', ]);
// WP QUERY
$query = new WP_Query([
'post_type' => 'press-release'
"posts_per_page => 25,
'category_name' => 'health',
]);

這可以通過自定義Loop來實現。本質上,迴圈是WordPress用來顯示某些文章的PHP程式碼。WordPress知道如何根據您的WP_Query自定義文章型別中的指定條件處理和格式化每個文章。

WP_Query對開發人員也很有幫助。您可以使用此PHP類自定義WordPress主題,而無需直接查詢資料庫。

如何使用WordPress WP_Query(4 種方式)

現在您已經瞭解了WP_Query,讓我們討論如何建立您的第一個查詢。這樣,您可以快速輕鬆地自定義您的網站顯示!

1.建立一個迴圈

您需要熟悉WordPress Loop才能開始使用。正如我們前面提到的,Loop負責從資料庫中提取文章資料。它根據主題的模板檔案確定內容的顯示方式。

根據您設定的引數,以下是Loop可以顯示的內容:

  • 來自WordPress自定義文章型別和自定義欄位的內容。
  • 在您的主頁上釋出標題和摘錄。
  • 單個文章的內容和評論。
  • 使用模板標籤的單個頁面內容。

在使用WP_Query自定義Loop之前,您需要了解Loop結構。這是一個基本迴圈的示例:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<?php
if ( have_posts() ) :
while ( have_posts() ) : the_post();
// Display post content
endwhile;
endif;
?>
<?php if ( have_posts() ) : while ( have_posts() ) : the_post(); // Display post content endwhile; endif; ?>
<?php
if ( have_posts() ) :
    while ( have_posts() ) : the_post();
        // Display post content
    endwhile;
endif;
?>

讓我們分解這個迴圈的各個部分。首先,函式have_posts()將檢查您的網站上是否有文章。如果是這樣,while條件會繼續每個文章的迴圈。本質上,這會通知您的資料庫在您的網站上顯示任何文章。

但是,您可能不想顯示所有文章。通過將WP_Query程式碼插入迴圈中,您可以使WordPress僅呈現某些文章:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
?php
// The Query
$the_query = new WP_Query( $args );
// The Loop
if ( $the_query->have_posts() ) {
echo '<ul>';
while ( $the_query->have_posts() ) {
$the_query->the_post();
echo '<li>' . get_the_title() . '</li>';
}
echo '</ul>';
} else {
// no posts found
}
/* Restore original Post Data */
wp_reset_postdata();
?php // The Query $the_query = new WP_Query( $args ); // The Loop if ( $the_query->have_posts() ) { echo '<ul>'; while ( $the_query->have_posts() ) { $the_query->the_post(); echo '<li>' . get_the_title() . '</li>'; } echo '</ul>'; } else { // no posts found } /* Restore original Post Data */ wp_reset_postdata();
?php
// The Query
$the_query = new WP_Query( $args );
// The Loop
if ( $the_query->have_posts() ) {
    echo '<ul>';
    while ( $the_query->have_posts() ) {
        $the_query->the_post();
        echo '<li>' . get_the_title() . '</li>';
    }
    echo '</ul>';
} else {
    // no posts found
}
/* Restore original Post Data */
wp_reset_postdata();

這包含與ifwhile語句相同的基本迴圈結構。但是,還有一個額外的WP_Query 字串。

您可以自定義Loop以僅根據您設定的引數顯示與特定WordPress分類、類別或作者關聯的文章。您還可以按日期、標籤、自定義欄位等縮小結果範圍。換句話說,在使用WP_Query自定義Loop時,您可以採取許多路線。

2. 使用引數

在構建WP_Query時,您需要包含四個基本元素:

  • Query argument
  • Query itself
  • The Loop
  • Post data reset

查詢中最關鍵的部分之一是引數(稱為WP_Query args)。該引數通知WordPress您要從資料庫中檢索哪些資料。該引數不會顯示您的所有文章內容,而是會在您的迴圈中設定一些條件。

您可能注意到了前面示例中的 ($args) 行。這是您將包含查詢引數的地方。

構造您的WP_Query args,您需要將某些引數放在一個陣列中。我們將在下一節討論引數,但下面是基本引數的外觀:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
$args = array(
'parameter1' => 'value',
'parameter2' => 'value',
'parameter3' => 'value'
);
$args = array( 'parameter1' => 'value', 'parameter2' => 'value', 'parameter3' => 'value' );
$args = array(
    'parameter1' => 'value',
    'parameter2' => 'value',
    'parameter3' => 'value'
);

例如,如果您想顯示具有“cooking”標籤的文章,您可以通過以下方式編寫引數:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
$query = new WP_Query( array( 'tag' => 'cooking' ) );
$query = new WP_Query( array( 'tag' => 'cooking' ) );
$query = new WP_Query( array( 'tag' => 'cooking' ) );

如果您不包含WP_Query引數,則不會從您的資料庫中提取任何內容。如果沒有這些資訊,WordPress將不知道要顯示哪些文章。

3. 設定引數

正如我們前面提到的,設定引數對於自定義WP_Query很重要。您可以通過指定此資訊使WordPress從您的資料庫中檢索自定義的文章集合。

如果您不確定要在引數中包含哪些引數,WordPress提供了許多不同用途的示例。由於這些已經為您編碼,因此可以在構建WP_Query時節省您的時間和精力。

以下是您可以使用的一些常用引數

  • Posts_per_page – 設定要顯示的文章數。
  • Author – 按一位或多位作者縮小結果範圍。
  • Cat – 指定結果應屬於的類別。
  • Tag – 拉出具有特定標籤的文章。
  • Orderby – 按作者、文章型別、日期等對結果進行排序。
  • Order – 按升序或降序對結果進行排序。
  • Post_type – 定義查詢是否應檢索文章、頁面或自定義文章型別。
  • Post_status – 指定文章是否正在進行、已安排、已釋出或已刪除。

例如,您可能需要顯示某個類別的文章。在這種情況下,您可以包含類別名稱和slug:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
$query = new WP_Query( array( 'category_name' => 'staff' ) );
$query = new WP_Query( array( 'category_name' => 'staff' ) );
$query = new WP_Query( array( 'category_name' => 'staff' ) );

這將拉取此WP_Query類別下的文章以及該類別的任何子項。

使用不同的引數,您還可以顯示特定日期的文章。要在工作日從上午9點到下午5點顯示內容,您將使用以下引數:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
$args = array(
'date_query' => array(
array(
'hour' => 9,
'compare' => '>=',
),
array(
'hour' => 17,
'compare' => '<=',
),
array(
'dayofweek' => array( 2, 6 ),
'compare' => 'BETWEEN',
),
),
'posts_per_page' => -1,
);
$query = new WP_Query( $args );
$args = array( 'date_query' => array( array( 'hour' => 9, 'compare' => '>=', ), array( 'hour' => 17, 'compare' => '<=', ), array( 'dayofweek' => array( 2, 6 ), 'compare' => 'BETWEEN', ), ), 'posts_per_page' => -1, ); $query = new WP_Query( $args );
$args = array(
    'date_query' => array(
        array(
            'hour'  	=> 9,
            'compare'   => '>=',
        ),
        array(
            'hour'  	=> 17,
            'compare'   => '<=',
        ),
        array(
            'dayofweek' => array( 2, 6 ),
            'compare'   => 'BETWEEN',
        ),
    ),
    'posts_per_page' => -1,
);
$query = new WP_Query( $args );

您可以使用的引數數量實際上是無限的。通過在您的引數中包含這些自定義條件,您的WP_Query可以成功地呈現正確的資料。

4.用方法修改類屬性

由於WP_Query是一個PHP類,它包含稱為屬性的常量。這些是PHP類的變數。

WordPress的開發人員建議不要直接更改WP_Query屬性。但是,您可以使用方法與它們進行互動。

方法的工作方式與函式類似。當您修改WP_Query的方法時,您可以自定義檢索到的資料。

在WP_Query的文件中,列出了許多基本任務的函式。例如,包含reset_postdata() 函式可能是編寫WP_Query的重要步驟。此方法將重置$current_post和$post的屬性。

這可能是這樣的:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<?php
// the query
$the_query = new WP_Query( $args ); ?>
<?php if ( $the_query->have_posts() ) : ?>
<!-- pagination here -->
<!-- the loop -->
<?php while ( $the_query->have_posts() ) : $the_query->the_post(); ?>
<h2><?php the_title(); ?></h2>
<?php endwhile; ?>
<!-- end of the loop -->
<!-- pagination here -->
<?php wp_reset_postdata(); ?>
<?php else : ?>
<p><?php _e( 'Sorry, no posts matched your criteria.' ); ?></p>
<?php endif; ?>
<?php // the query $the_query = new WP_Query( $args ); ?> <?php if ( $the_query->have_posts() ) : ?> <!-- pagination here --> <!-- the loop --> <?php while ( $the_query->have_posts() ) : $the_query->the_post(); ?> <h2><?php the_title(); ?></h2> <?php endwhile; ?> <!-- end of the loop --> <!-- pagination here --> <?php wp_reset_postdata(); ?> <?php else : ?> <p><?php _e( 'Sorry, no posts matched your criteria.' ); ?></p> <?php endif; ?>
<?php
// the query
$the_query = new WP_Query( $args ); ?>
 
<?php if ( $the_query->have_posts() ) : ?>
 
    <!-- pagination here -->
 
    <!-- the loop -->
    <?php while ( $the_query->have_posts() ) : $the_query->the_post(); ?>
        <h2><?php the_title(); ?></h2>
    <?php endwhile; ?>
    <!-- end of the loop -->
 
    <!-- pagination here -->
 
    <?php wp_reset_postdata(); ?>
 
<?php else : ?>
    <p><?php _e( 'Sorry, no posts matched your criteria.' ); ?></p>
<?php endif; ?>

最終,如果您在查詢中使用the_post()函式,則必須使用此方法。這可確保模板標籤使用主查詢的當前文章。

以下是一些可用於修改WP_Query屬性的其他方法:

  • get_posts– 根據給定變數檢索後陣列。
  • have_posts– 確定文章是否在迴圈中可用。
  • generate_postdata– 顯示文章。
  • fill_query_vars– 完成引數中未列出的查詢變數。

根據您提供的資訊,您可以自定義WP_Query以執行所需的功能。這是修改類屬性的一種靈活、安全的方法。

WP_Query的例子

一旦您瞭解了WordPress的WP_Query的基礎知識,您就可以開始使用它來自定義您的網站設計。由於您可以定義各種引數,因此選項幾乎是無窮無盡的。

讓我們討論一些常見的WP_Query示例,給您一些啟發!

1. 某一分類的最新文章

一般來說,線上使用者對新內容最感興趣。訪問者閱讀您的一篇文章後,您需要提供一些相關內容。通過推薦類似的、更新的文章,您可以將使用者引導至他們可能喜歡的其他內容。

此WP_Query對於具有時間敏感文章的網站特別有用。例如,訪問者可能會閱讀有關記憶喪失的科學文章。使用WP_Query,您可以通過最新研究突出顯示類似主題:

某分類文章推薦

如果您想提取特定類別中的最新文章,請貼上此WP_Query:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<?php
// Get the current post id.
$current_post_id = get_the_ID();
// Get the current post's category (first one if there's more than one).
$current_post_cats = get_the_category();
$current_post_first_cat_id = $current_post_cats[ 0 ]->term_id;
// Setup arguments.
$args = array(
// Get category's posts.
'cat' => $current_post_first_cat_id,
// Exclude current post.
'post__not_in' => array( $current_post_id )
);
// Instantiate new query instance.
$my_query = new WP_Query( $args );
?>
<?php // Get the current post id. $current_post_id = get_the_ID(); // Get the current post's category (first one if there's more than one). $current_post_cats = get_the_category(); $current_post_first_cat_id = $current_post_cats[ 0 ]->term_id; // Setup arguments. $args = array( // Get category's posts. 'cat' => $current_post_first_cat_id, // Exclude current post. 'post__not_in' => array( $current_post_id ) ); // Instantiate new query instance. $my_query = new WP_Query( $args ); ?>
<?php
 
// Get the current post id.
$current_post_id = get_the_ID();
 
// Get the current post's category (first one if there's more than one).
$current_post_cats = get_the_category();
$current_post_first_cat_id = $current_post_cats[ 0 ]->term_id;
 
// Setup arguments.
$args = array(
    // Get category's posts.
    'cat' => $current_post_first_cat_id,
    // Exclude current post.
    'post__not_in' => array( $current_post_id )
);
 
// Instantiate new query instance.
$my_query = new WP_Query( $args );
 
?>

使用您網站的資訊編輯此查詢後,您可以顯示與訪問者剛剛閱讀的文章相似的文章。這可以有效地將使用者引導至相關的當前資訊,而無需搜尋。

2. 本週釋出的文章

如果您有專門的追隨者,讀者會希望在您的最新文章發表後立即閱讀它們。當您可以設計您的網站以展示最近的文章時,您可以提供最相關的資訊。

特別是如果您託管一個新聞網站,您需要將您的文章從最新到最舊格式化。這樣做可以使使用者快速輕鬆地找到對時間敏感的內容。

最新發布文章列表

使用WP_Query,您可以根據文章的日期設定引數。通過僅檢索過去一週釋出的文章,您可以防止使用者看到過時的文章:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<?php
$arguments = array(
"date_query" => array(
array(
"year" => date( "Y" ),
"week" => date( "W" ),
)
)
);
$posts = new WP_Query($arguments);
?>
<?php $arguments = array( "date_query" => array( array( "year" => date( "Y" ), "week" => date( "W" ), ) ) ); $posts = new WP_Query($arguments); ?>
<?php  
   $arguments = array(
      "date_query" => array(
         array(
           "year" => date( "Y" ),
           "week" => date( "W" ),
         )
      )
   );
   $posts = new WP_Query($arguments);
?>

當您自定義date_query引數,您可以定位最近釋出的文章。儘管您可以包含自己的自定義值,但突出顯示過去一週撰寫的文章可能會很有效。

同樣,您可以宣傳大多數觀眾喜歡的文章。通過通知使用者另一個文章獲得了很多參與,它可以鼓勵他們點選文章以瞭解更多資訊。

由於WordPress不會跟蹤您的文章檢視次數,您可能需要自己新增此功能。您可以使用外掛來執行此操作,但這會降低您的網站速度。

使用WP_Query,您可以根據評論數量推薦其他熱門文章。這樣可以輕鬆顯示您最喜歡的文章:

更受歡迎文章推薦

以下是可用於根據受歡迎程度構建推薦的資料:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<?php
// Setup arguments.
$args = array(
// Order by comment count.
'orderby' => 'comment_count'
);
// Instantiate new query instance.
$my_query = new WP_Query( $args );
?>
<?php // Setup arguments. $args = array( // Order by comment count. 'orderby' => 'comment_count' ); // Instantiate new query instance. $my_query = new WP_Query( $args ); ?>
<?php
 
// Setup arguments.
$args = array(
    // Order by comment count.
    'orderby' => 'comment_count'
);
 
// Instantiate new query instance.
$my_query = new WP_Query( $args );
 
?>

您還可以根據某個類別縮小這些結果的範圍。只需新增一個帶有您的類別名稱的引數:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<?php
$arguments = array(
"category_name" => "fiction",
"orderby" => "comment_count",
"posts_per_page" => 5,
);
$posts = new WP_Query($arguments);
?>
<?php $arguments = array( "category_name" => "fiction", "orderby" => "comment_count", "posts_per_page" => 5, ); $posts = new WP_Query($arguments); ?>
<?php  
   $arguments = array(
      "category_name" => "fiction",
      "orderby" => "comment_count",
      "posts_per_page" => 5,
   );
   $posts = new WP_Query($arguments);
?>

這也將建議限制為五個職位。如果需要,您可以使用不同的數字編輯此值。

4.同一作者和類別的文章

當訪問者閱讀您的部落格文章時,他們可能真的很喜歡該內容。他們可能只是更喜歡作者的寫作風格或一般主題。

在這種情況下,您可以使用WP_Query提供類似的文章推薦。這樣,讀者可以點選其他文章繼續閱讀:

作者相關文章推薦

要構建一行類似的文章,您需要實現一個特定的WP_Query字串。這將在您的網站上搜尋具有相同作者和文章類別的部落格文章。

這是您可以使用的程式碼:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<?php
$arguments = array(
"author_name" => "john",
"category_name" => "fiction",
"posts_per_page" => 3,
);
$posts = new WP_Query($arguments);
?>
<?php $arguments = array( "author_name" => "john", "category_name" => "fiction", "posts_per_page" => 3, ); $posts = new WP_Query($arguments); ?>
<?php  
   $arguments = array(
      "author_name" => "john",
      "category_name" => "fiction",
      "posts_per_page" => 3,
   );
   $posts = new WP_Query($arguments);
?>

實現此程式碼時,您需要將‘john’替換為作者的姓名。然後,刪除“fiction”幷包含您的類別標籤。最後,隨意修改頁面上顯示的文章推薦數量。

5. 作者的年釋出文章

如果你經營一個更突出的部落格,你可能有很多不同的作者寫文章。有人閱讀您的一篇文章後,他們可能希望更輕鬆地找到該作者的其他文章。

在這種情況下,您可以列出作者在過去一年中的文章。這可以為訪問者提供有關作者的資訊以及他們以前的作品列表:

作者文章歸檔頁

要開發作者的年度文章列表,您可以使用此 WP_Query:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<?php
// Get the year we're in.
$current_year = date( 'Y' );
// Setup arguments.
$args = array(
// Get the author with the nicename "john".
'author' => 'john',
// Get his posts from this year.
'year' => $current_year
);
// Instantiate new query instance.
$my_query = new WP_Query( $args );
?>
<?php // Get the year we're in. $current_year = date( 'Y' ); // Setup arguments. $args = array( // Get the author with the nicename "john". 'author' => 'john', // Get his posts from this year. 'year' => $current_year ); // Instantiate new query instance. $my_query = new WP_Query( $args ); ?>
<?php
 
// Get the year we're in.
$current_year = date( 'Y' );
 
// Setup arguments.
$args = array(
    // Get the author with the nicename "john".
    'author' => 'john',
    // Get his posts from this year.
    'year'   => $current_year
);
 
// Instantiate new query instance.
$my_query = new WP_Query( $args );
 
?>

此資料將提取特定作者撰寫的所有文章。它還將根據本年度細化這些結果。例如,它不會列出一年多以前發表的任何文章。

6.預覽計劃釋出的文章

為了讓您的觀眾先睹為快,您可以在您的網站上列出您預定的文章。使用WP_Query,您可以顯示新文章的標題和摘錄。

這有助於在您釋出文章之前引起對文章的興趣。另外,使用WP_Query很容易實現:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<?php
/*
* Usage with Excerpts:
*
* <?php echo tutsplus_show_drafts(); ?>
*
* Usage without Excerpts:
*
* <?php echo tutsplus_show_drafts( false ); ?>
*/
function tutsplus_show_drafts( $show_excerpts = true ) {
// Setup arguments.
$args = array(
'post_status' => 'future',
'nopaging' => true
);
// Instantiate new query instance.
$my_query = new WP_Query( $args );
// Check that we have query results.
if ( $my_query->have_posts() ) {
// Begin generating markup.
$output = '<section class="pending-posts">';
// Start looping over the query results.
while ( $my_query->have_posts() ) {
$my_query->the_post();
// Output draft post title and excerpt (if enabled).
$output .= '<div class="pending">';
$output .= '<h3 class="pending-title">' . get_the_title() . '</h3>';
$output .= get_the_title();
$output .= '</h3>';
if ( $show_excerpts ) {
$output .= '<div class="pending-excerpt">';
$output .= get_the_excerpt();
$output .= '</div>';
}
$output .= '</div>';
}
// End generating markup.
$output .= '</section>';
} else {
// Let user know that nothing was found.
$output = '<section class="drafts-error">';
$output .= '<p>' . __( 'Nothing found', 'tutsplus' ) . '</p>';
$output .= '</section>';
}
wp_reset_postdata();
return $output;
}
?>
<?php /* * Usage with Excerpts: * * <?php echo tutsplus_show_drafts(); ?> * * Usage without Excerpts: * * <?php echo tutsplus_show_drafts( false ); ?> */ function tutsplus_show_drafts( $show_excerpts = true ) { // Setup arguments. $args = array( 'post_status' => 'future', 'nopaging' => true ); // Instantiate new query instance. $my_query = new WP_Query( $args ); // Check that we have query results. if ( $my_query->have_posts() ) { // Begin generating markup. $output = '<section class="pending-posts">'; // Start looping over the query results. while ( $my_query->have_posts() ) { $my_query->the_post(); // Output draft post title and excerpt (if enabled). $output .= '<div class="pending">'; $output .= '<h3 class="pending-title">' . get_the_title() . '</h3>'; $output .= get_the_title(); $output .= '</h3>'; if ( $show_excerpts ) { $output .= '<div class="pending-excerpt">'; $output .= get_the_excerpt(); $output .= '</div>'; } $output .= '</div>'; } // End generating markup. $output .= '</section>'; } else { // Let user know that nothing was found. $output = '<section class="drafts-error">'; $output .= '<p>' . __( 'Nothing found', 'tutsplus' ) . '</p>'; $output .= '</section>'; } wp_reset_postdata(); return $output; } ?>
<?php
 
/*
 * Usage with Excerpts:
 *
 * <?php echo tutsplus_show_drafts(); ?>
 *
 * Usage without Excerpts:
 *
 * <?php echo tutsplus_show_drafts( false ); ?>
 */
 
function tutsplus_show_drafts( $show_excerpts = true ) {
 
    // Setup arguments.
    $args = array(
        'post_status' => 'future',
        'nopaging' => true
    );
 
    // Instantiate new query instance.
    $my_query = new WP_Query( $args );
 
    // Check that we have query results.
    if ( $my_query->have_posts() ) {
 
        // Begin generating markup.
        $output = '<section class="pending-posts">';
 
        // Start looping over the query results.
        while ( $my_query->have_posts() ) {
 
            $my_query->the_post();
 
            // Output draft post title and excerpt (if enabled).
            $output .= '<div class="pending">';
                $output .= '<h3 class="pending-title">' . get_the_title() . '</h3>';
                    $output .= get_the_title();
                $output .= '</h3>';
 
                if ( $show_excerpts ) {
 
                    $output .= '<div class="pending-excerpt">';
                        $output .= get_the_excerpt();
                    $output .= '</div>';
 
                }
 
            $output .= '</div>';
 
        }
 
        // End generating markup.
        $output .= '</section>';
 
    } else {
 
        // Let user know that nothing was found.
        $output = '<section class="drafts-error">';
            $output .= '<p>' . __( 'Nothing found', 'tutsplus' ) . '</p>';
        $output .= '</section>';
 
    }
 
    wp_reset_postdata();
 
    return $output;
 
}
 
?>

這將自動設定您預定的文章標題的預覽。如果需要,您還可以包含摘錄。

小結

WP_Query提供了一種更簡單的方式來執行WordPress資料庫請求。使用這個PHP類,您可以自定義站點的顯示併為每個線上訪問者提供獨特的體驗。

以下是您可以在WordPress中使用WP_Query的四種方式:

  1. 建立一個迴圈。
  2. 使用查詢引數。
  3. 設定具體引數。
  4. 修改類屬性。

當您掌握了WordPress這些WP_Query技術的竅門後,您將能夠根據受歡迎程度、日期、作者等來推薦特定的文章。

評論留言