如何使用PHP函式get_posts來構建文章列表

如何使用PHP函式get_posts來構建文章列表

WordPress的get_posts是一個強大的函式,允許開發人員從WordPress資料庫中檢索內容。您可以最詳細地指定要查詢的文章、頁面和自定義文章型別,獲取自定義結果集,然後像PHP/MySQL忍者一樣過濾和排序專案。

但是,如果您不是PHP專業人士,請不要害怕,有無數的PHP教學可供您觀看或閱讀並學習該語言。您只需要一點PHP知識即可建立自定義文章列表以顯示在您的網站上,因為get_posts函式保留了一組引數,允許構建簡單或高階查詢。

使用WordPress的get_posts分為兩個步驟:

  • 首先,您必須構建自定義查詢。實際上,它看起來不像MySQL查詢,而且您不會編寫任何SELECT語句。您只需要定義一個引數陣列並將其傳遞給get_posts函式。WordPress將該陣列轉換為真實且安全的MySQL查詢,針對資料庫執行它,並返回一個文章陣列。
  • 其次,您必須使用foreach迴圈遍歷get_posts返回的結果集。

話雖如此,在這篇文章中,我們將首先深入探討上面提到的關鍵概念,特別是如何get_posts工作、如何構建自定義查詢以及如何在前端站點上顯示資料。然後,我將提供一個真實示例,其中包含一段程式碼,您可以在暫存環境中獲取、編輯和使用程式碼片段,以進行測試和開發。

注意:我們通常區分文章、頁面和自定義文章型別。在本文中,我們使用術語“post”來表示常規部落格文章以及頁面和自定義文章型別。所有這些文章型別都儲存在資料庫的“wp_posts”表中。文章型別之間的主要區別在於“post_type”欄位的值。從開發人員的角度來看,文章、頁面和自定義文章型別都是文章

get_posts 函式簡介

Codex對get_posts函式的描述如下:

檢索最新文章的陣列,或與給定條件匹配的文章。

我們可以這樣使用get_posts

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
$args = array(
'numberposts' => 20,
'category' => 4
);
$my_posts = get_posts( $args );
if( ! empty( $my_posts ) ){
$output = '<ul>';
foreach ( $my_posts as $p ){
$output .= '<li><a href="' . get_permalink( $p->ID ) . '">'
. $p->post_title . '</a></li>';
}
$output .= '</ul>';
}
$args = array( 'numberposts' => 20, 'category' => 4 ); $my_posts = get_posts( $args ); if( ! empty( $my_posts ) ){ $output = '<ul>'; foreach ( $my_posts as $p ){ $output .= '<li><a href="' . get_permalink( $p->ID ) . '">' . $p->post_title . '</a></li>'; } $output .= '</ul>'; }
$args = array(
'numberposts'	=> 20,
'category'		=> 4
);
$my_posts = get_posts( $args );
if( ! empty( $my_posts ) ){
$output = '<ul>';
foreach ( $my_posts as $p ){
$output .= '<li><a href="' . get_permalink( $p->ID ) . '">' 
. $p->post_title . '</a></li>';
}
$output .= '</ul>';
}

上面的函式檢索指定類別中的最新20篇博文(預設為'post_type'is 'post')並返回一個物件陣列$post。您可以遍歷陣列以在螢幕上顯示文章。這很容易,對吧?

get_posts 用於WP_Query檢索文章專案,並且它保留了一個包含相同引數的陣列WP_Query(除了少數例外)。所以我們有一個龐大的變數列表,可以用來構建我們的自定義查詢。這些引數分為以下15個類別

  • Author引數
  • Category引數
  • Tag引數
  • Taxonomy引數
  • Search引數
  • Post & Page引數
  • Password引數
  • Post Type引數
  • Order & Orderby引數
  • Date引數
  • Custom Field (post meta) 引數
  • Permission引數
  • Mime Type引數
  • Caching引數
  • Return Fields引數

快速檢視上面的列表可以讓您瞭解可以針對WordPress資料庫構建和執行的各種自定義查詢。因此,讓我們更深入地研究查詢引數並開始構建我們的文章列表。

如何使用get_posts構建查詢

每一類引數都與同一條資訊相關。例如,我們可以構建一個查詢來檢索指定作者或排除指定作者的文章,通過ID或nicename定義作者。同樣,我們可以構建查詢,按類別、標籤、分類、日期、自定義欄位等獲取文章。

如何使用引數構建簡單查詢

許多引數可以以非常相似的方式使用,無論它們屬於哪個類別。例如,以下引數允許按文章作者查詢資料庫:

  • authorint ) – 作者ID
  • author_name字串)——作者的user_nicename
  • author__inarray ) – 多個作者ID的陣列
  • author__not_inarray ) — 要從結果集中排除的多個作者ID的陣列

我們如何使用這些引數?

在以下示例中,引數'author' 指定我們想要ID = 1的作者最近撰寫的部落格文章:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
$my_posts = get_posts( array( 'author' => 1 ) );
$my_posts = get_posts( array( 'author' => 1 ) );
$my_posts = get_posts( array( 'author' => 1 ) );

相同的 ‘author’引數允許以不同的方式查詢資料庫:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
// return an array of posts from specific authors
$my_posts = get_posts( array( 'author' => '1,5,12' ) );
// return an array of posts from specific authors $my_posts = get_posts( array( 'author' => '1,5,12' ) );
// return an array of posts from specific authors
$my_posts = get_posts( array( 'author' => '1,5,12' ) );
Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
// return an array of posts excluding the specified author
$my_posts = get_posts( array( 'author' => -1 ) );
// return an array of posts excluding the specified author $my_posts = get_posts( array( 'author' => -1 ) );
// return an array of posts excluding the specified author
$my_posts = get_posts( array( 'author' => -1 ) );

因此,根據引數的值,您將獲得一個結果集,其中包含來自單個作者(整數)、來自多個作者(逗號分隔值列表)或不包括作者(負值)的文章。

其他引數提供了額外的靈活性。例如,以下呼叫get_posts返回多個作者的最新部落格文章陣列:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
// return an array of posts from multiple authors
$my_posts = get_posts( array( 'author__in' => array( 1, 5, 12 ) ) );
// return an array of posts from multiple authors $my_posts = get_posts( array( 'author__in' => array( 1, 5, 12 ) ) );
// return an array of posts from multiple authors
$my_posts = get_posts( array( 'author__in' => array( 1, 5, 12 ) ) );

我們還可以排除多個作者:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
// return an array of posts from multiple authors
$my_posts = get_posts( array( 'author__not_in' => array( 1, 5, 12 ) ) );
// return an array of posts from multiple authors $my_posts = get_posts( array( 'author__not_in' => array( 1, 5, 12 ) ) );
// return an array of posts from multiple authors
$my_posts = get_posts( array( 'author__not_in' => array( 1, 5, 12 ) ) );

同樣,我們可以使用類別引數、標籤引數、文章型別引數,但有一些具體的區別。例如,請參見類別引數:

  • cat整數
  • category_name字串
  • category__and陣列
  • category__in陣列
  • category__not_in陣列

無論如何,並非所有引數都像這些引數一樣易於使用。此外,我們可以在單個查詢中使用類別引數、文章型別引數、mime型別引數等。這意味著我們可以對結果集中的專案進行精細控制,並且可以完全基於文章型別、自定義分類法和自定義欄位構建更高階的查詢。

所以,讓我們更深入地研究吧!

如何在WordPress中構建高階查詢

讓我們通過基於自定義文章型別和自定義分類的更高階查詢向前邁出一步。假設您有以下文章型別:

名稱:書籍

分類名稱:book_category、book_author

支援:標題、編輯器、縮圖、摘錄、自定義欄位

自定義文章型別和自定義分類法

假設您想要指定自定義分類book_category中最新書籍的列表。這是引數陣列:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
$args = array(
'post_type' => 'book',
'tax_query' => array(
array(
'taxonomy' => 'book_category',
'field' => 'slug',
'terms' => 'sci-fi'
)
),
);
$args = array( 'post_type' => 'book', 'tax_query' => array( array( 'taxonomy' => 'book_category', 'field' => 'slug', 'terms' => 'sci-fi' ) ), );
$args = array(
'post_type'		=> 'book',
'tax_query'		=> array(
array(
'taxonomy'	=> 'book_category',
'field'		=> 'slug',
'terms'		=> 'sci-fi'
)
),
);

上面的引數只是告訴WordPress檢索'sci-fi' 'book_category'.

引數採用'tax_query'引數陣列的陣列(即陣列陣列)。這些巢狀陣列允許基於多種分類構建非常複雜的查詢,如下例所示:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
$args = array(
'numberposts' => 10,
'post_type' => 'book',
'relation' => 'AND',
'tax_query' => array(
array(
'taxonomy' => 'book_category',
'field' => 'slug',
'terms' => 'sci-fi'
),
array(
'taxonomy' => 'book_author',
'field' => 'term_id',
'terms' => 22
)
)
);
$args = array( 'numberposts' => 10, 'post_type' => 'book', 'relation' => 'AND', 'tax_query' => array( array( 'taxonomy' => 'book_category', 'field' => 'slug', 'terms' => 'sci-fi' ), array( 'taxonomy' => 'book_author', 'field' => 'term_id', 'terms' => 22 ) ) );
$args = array(
'numberposts'	=> 10,
'post_type'		=> 'book',
'relation'		=> 'AND',
'tax_query'		=> array(
array(
'taxonomy'	=> 'book_category',
'field'		=> 'slug',
'terms'		=> 'sci-fi'
),
array(
'taxonomy'	=> 'book_author',
'field'		=> 'term_id',
'terms'		=> 22
)
)
);

這些引數允許我們檢索由ID #22編寫的最新10個'book'文章型別的列表。該引數設定 中列出的每個分類之間的邏輯關係。上面我們將其值設定為,因為我們需要檢索屬於作者 #22 所寫類別的所有書籍。AND

這些引數允許我們檢索由ID為#22的'book_author'編寫的'sci-fi''book_category'中最新10種“book”文章型別的列表。'relation'引數設定'tax_query'中列出的每個分類法之間的邏輯關係。在上面,我們將其值設定為AND,因為我們需要檢索屬於 'sci-fi'類別AND 由作者#22撰寫的所有書籍。

 

如何使用自定義欄位引數構建元查詢

有時,您可能需要根據特定的自定義欄位鍵和/或值構建文章列表。

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
$args = array(
'meta_key' => 'cover',
'meta_value' => 'paperback',
'meta_compare' => '='
);
$args = array( 'meta_key' => 'cover', 'meta_value' => 'paperback', 'meta_compare' => '=' );
$args = array(
'meta_key'		=> 'cover',
'meta_value'	=> 'paperback',
'meta_compare'	=> '='
);

這些引數允許我們通過自定義欄位鍵和值檢索所有文章。'meta_compare'設定測試'meta_value'引數值所需的運算子。這裡的'meta_value''=',這也是預設值。

可用值為'=''!=''>''>=''<''<=''LIKE''NOT LIKE''IN''NOT IN''BETWEEN''NOT BETWEEN''NOT EXISTS''REGEXP','NOT REGEXP''RLIKE'.

這是一個非常簡單的示例,但我們可以構建更高階的查詢。在下一個示例中,我們在資料庫中查詢2010年之後出版的奇幻書籍:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
$args = array(
'post_type' => 'book',
'meta_key' => 'year_published',
'meta_value_num' => 2010,
'meta_compare' => '>',
'tax_query' => array(
array(
'taxonomy' => 'book_category',
'field' => 'slug'
'terms' => 'fantasy'
)
)
);
$args = array( 'post_type' => 'book', 'meta_key' => 'year_published', 'meta_value_num' => 2010, 'meta_compare' => '>', 'tax_query' => array( array( 'taxonomy' => 'book_category', 'field' => 'slug' 'terms' => 'fantasy' ) ) );
$args = array(
'post_type'		=> 'book',
'meta_key'		=> 'year_published',
'meta_value_num'	=> 2010,
'meta_compare'	=> '>',
'tax_query'		=> array(
array(
'taxonomy'	=> 'book_category',
'field'		=> 'slug'
'terms'		=> 'fantasy'
)
)
);

我們可以走得更遠。在下一個示例中,我們將一個文章型別與一個自定義分類法和兩個自定義欄位混合在一起:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
$args = array(
'post_type' => 'book',
'tax_query' => array(
array(
'taxonomy' => 'book_category',
'field' => 'slug'
'terms' => array( 'fantasy' )
)
),
'meta_query' => array(
'relation' => 'AND',
array(
'key' => 'year_published',
'value' => 2010,
'type' => 'numeric',
'compare' => '>',
),
array(
'key' => 'price',
'value' => array( 10, 25 ),
'type' => 'numeric',
'compare' => 'BETWEEN',
)
)
);
$args = array( 'post_type' => 'book', 'tax_query' => array( array( 'taxonomy' => 'book_category', 'field' => 'slug' 'terms' => array( 'fantasy' ) ) ), 'meta_query' => array( 'relation' => 'AND', array( 'key' => 'year_published', 'value' => 2010, 'type' => 'numeric', 'compare' => '>', ), array( 'key' => 'price', 'value' => array( 10, 25 ), 'type' => 'numeric', 'compare' => 'BETWEEN', ) ) );
$args = array(
'post_type'		=> 'book',
'tax_query'		=> array(
array(
'taxonomy'	=> 'book_category',
'field'		=> 'slug'
'terms'		=> array( 'fantasy' )
)
),
'meta_query'	=> array(
'relation'		=> 'AND',
array(
'key'		=> 'year_published',
'value'		=> 2010,
'type'		=> 'numeric',
'compare'	=> '>',
),
array(
'key'		=> 'price',
'value'		=> array( 10, 25 ),
'type'		=> 'numeric',
'compare'	=> 'BETWEEN',
)
)
);

在這裡,我們設定了一組引數來檢索2010年之後出版的幻想書籍列表,這些書籍的價格分別BETWEEN為10美元和25美元。

您可以看到'meta_query'引數的工作方式與引數非常相似'tax_query'。它保留了一個陣列陣列,允許我們基於多個元鍵/值對構建高階查詢。有關查詢引數的完整列表和大量示例,請參閱WP_Query文件

為什麼get_posts僅限於5個WordPress文章?

get_posts 函式採用與WP_Query::parse_query()參見Codex)相同的引數,但某些特定引數使其與WP_Query物件的工作方式略有不同。

也許您沒有在查詢中使用'numberposts'引數,並且想知道為什麼您的列表中只看到5個專案。

預設情況下,您在設定 → 閱讀管理頁面中設定的文章數量決定了WordPress查詢要檢索的文章數量。無論如何,如果您沒有為'numberposts'或者'posts_per_page'指定自定義值,則get_posts返回不同數量的文章。

  • 'numberposts'是要檢索的文章總數。它是'posts_per_page'inWP_Query的別名,但兩者之間有區別:預設情況下,使用get_posts時要檢索的文章數為 5,而'posts_per_page'inWP_Query預設為WordPress部落格每頁的文章數。您可以通過為引數陣列'numberposts''posts_per_page'在引數陣列中設定自定義值來覆蓋預設值。

除了'numberposts'之外,以下引數是特定於get_posts的:

  • 'category'是一個以逗號分隔的類別ID列表。它是WP_Query'cat'引數的別名。
  • 'include'是一個逗號分隔的文章ID列表。這是WP_Query'post__in'引數的別名。
  • 'exclude'是一個逗號分隔的文章ID列表。
  • 'suppress_filters'指定是否抑制過濾器。此引數預設為trueinget_posts,而預設為falseinWP_Query參見Track)。

get_posts函式在wp-includes/post.php中定義。get_posts您可以通過檢視Track (WordPress 5.2)或本地WordPress安裝中的原始碼來深入瞭解其工作原理。

專案排序

'orderby''order'並結果集中的專案進行排序。您可以按'ID''author''title''name''type''date''modified''parent','rand''comment_count'許多其他方式按升序或降序對文章進行排序。

如果您有一個簡單的查詢,您只需要為'order''orderby'設定一個值。在以下示例中,文章按文章名稱升序排序:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
$args = array(
'author' => '1,5,12',
'orderby' => 'name',
'order' => 'ASC'
);
$args = array( 'author' => '1,5,12', 'orderby' => 'name', 'order' => 'ASC' );
$args = array(
'author'	=> '1,5,12',
'orderby'	=> 'name',
'order'		=> 'ASC'
);

這很簡單。但是如果你有一個高階查詢呢?即:我們可以在高階元查詢中按一個或多個自定義欄位值對專案進行排序嗎?

WordPress 4.0和WordPress 4.2帶來了重要的改進'orderby''meta_query'引數。我們現在有了一種新的語法,用於按元查詢的特定子句進行排序。由於新的語法,我們可以使用索引從'orderby'引數建立對元查詢的特定子句的引用。

由於這些改進,上例中的元查詢可以寫成如下:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
$args = array(
'meta_query' => array(
'relation' => 'AND',
'year_clause' => array(
'key' => 'year_published',
'value' => 2010,
'type' => 'numeric',
'compare' => '>',
),
'price_clause' => array(
'key' => 'price',
'value' => array( 10, 25 ),
'type' => 'numeric',
'compare' => 'BETWEEN',
)
),
'orderby' => 'price_clause',
);
$args = array( 'meta_query' => array( 'relation' => 'AND', 'year_clause' => array( 'key' => 'year_published', 'value' => 2010, 'type' => 'numeric', 'compare' => '>', ), 'price_clause' => array( 'key' => 'price', 'value' => array( 10, 25 ), 'type' => 'numeric', 'compare' => 'BETWEEN', ) ), 'orderby' => 'price_clause', );
$args = array(
'meta_query'	=> array(
'relation'		=> 'AND',
'year_clause' => array(
'key'		=> 'year_published',
'value'		=> 2010,
'type'		=> 'numeric',
'compare'	=> '>',
),
'price_clause' => array(
'key'		=> 'price',
'value'		=> array( 10, 25 ),
'type'		=> 'numeric',
'compare'	=> 'BETWEEN',
)
),
'orderby' => 'price_clause',
);

在上面的示例中,我們對'price_clause'元素進行了排序。

我們可以做得更多。從WordPress 4.0開始,我們可以傳遞給get_posts元查詢索引陣列而不是單個索引,如下例所示:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
$args = array(
'meta_query' => array(
'relation' => 'AND',
'year_clause' => array(
'key' => 'year_published',
'value' => 2010,
'type' => 'numeric',
'compare' => '>',
),
'price_clause' => array(
'key' => 'price',
'value' => array( 10, 25 ),
'type' => 'numeric',
'compare' => 'BETWEEN',
)
),
'orderby' => array( 'price_clause' => 'ASC', 'year_clause' => 'DESC' ),
);
$args = array( 'meta_query' => array( 'relation' => 'AND', 'year_clause' => array( 'key' => 'year_published', 'value' => 2010, 'type' => 'numeric', 'compare' => '>', ), 'price_clause' => array( 'key' => 'price', 'value' => array( 10, 25 ), 'type' => 'numeric', 'compare' => 'BETWEEN', ) ), 'orderby' => array( 'price_clause' => 'ASC', 'year_clause' => 'DESC' ), );
$args = array(
'meta_query'	=> array(
'relation'		=> 'AND',
'year_clause' => array(
'key'		=> 'year_published',
'value'		=> 2010,
'type'		=> 'numeric',
'compare'	=> '>',
),
'price_clause' => array(
'key'		=> 'price',
'value'		=> array( 10, 25 ),
'type'		=> 'numeric',
'compare'	=> 'BETWEEN',
)
),
'orderby' => array( 'price_clause' => 'ASC', 'year_clause' => 'DESC' ),
);

恭喜,您已經構建了一個高階元查詢,並首先按'price_clause'升序對結果進行排序,然後按'year_clause'降序排序。

請參閱Codex中排序選項的完整列表

是時候在首頁上顯示資料了。

推薦閱讀:如何輕鬆建立和使用phpinfo頁面

如何顯示get_posts返回的資料

WordPress的get_posts返回一個WP_Post物件陣列,讓我們可以訪問儲存在wp_posts資料庫表中的每個選定文章的許多變數:

  • ID
  • post_author
  • post_name
  • post_type
  • post_title
  • post_date
  • post_date_gmt
  • post_content
  • post_excerpt
  • post_status
  • comment_status
  • ping_status
  • post_password
  • post_parent
  • post_modified
  • post_modified_gmt
  • comment_count
  • menu_order

phpMyAdmin中的wp_posts表結構

phpMyAdmin中的wp_posts表結構

您可以使用foreach迴圈輕鬆訪問這些資料,如下:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
$custom_posts = get_posts( $args );
if( ! empty( $custom_posts ) ){
$output = '<ul>';
foreach ( $custom_posts as $p ){
$output .= '<li><a href="'
. get_permalink( $p->ID ) . '">'
. $p->post_title . '</a></li>';
}
$output .= '</ul>';
}
return $output ?? '<strong>Sorry. No posts matching your criteria!</strong>';
$custom_posts = get_posts( $args ); if( ! empty( $custom_posts ) ){ $output = '<ul>'; foreach ( $custom_posts as $p ){ $output .= '<li><a href="' . get_permalink( $p->ID ) . '">' . $p->post_title . '</a></li>'; } $output .= '</ul>'; } return $output ?? '<strong>Sorry. No posts matching your criteria!</strong>';
$custom_posts = get_posts( $args );
if( ! empty( $custom_posts ) ){
$output = '<ul>';
foreach ( $custom_posts as $p ){
$output .= '<li><a href="' 
. get_permalink( $p->ID ) . '">' 
. $p->post_title . '</a></li>';
}
$output .= '</ul>';
}
return $output ?? '<strong>Sorry. No posts matching your criteria!</strong>';

如果get_posts找到至少一個文章,它會返回一個我們可以遍歷的專案陣列,以顯示文章標題和指向原始文章的連結。我們使用get_permalink函式來檢索文章永久連結,因為我們沒有相應的WP_Post變數。

這很簡單,但是我們如何實現該程式碼並使用WordPress構建我們的自定義文章列表get_posts

您可以通過多種方式在頁面上顯示文章列表。

真實示例:如何使用簡碼顯示自定義專案列表

我將向您展示如何構建可以包含在內容中的快速簡便的短程式碼。無論如何,我不會深入研究短程式碼,因為我們已經在之前的部落格文章中介紹了該主題。

首先,在本地WordPress安裝wp-content/plugins資料夾或臨時環境中建立一個新目錄。在此示例中,我將目錄命名為wbolt-shortcodes

在建立一個與新目錄同名的 .php 檔案:.wp-content/plugins/wbolt-shortcodes/wbolt-shortcodes.php

在您喜歡的文字編輯器中開啟新檔案幷包含以下標題:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<?php
/**
* @package Wbolt_shortcodes
* @version 1.0
*/
/*
Plugin Name: Wbolt shortcodes
Plugin URI: http://wordpress.org/extend/plugins/#
Description: This is an example plugin
Author: Your Name
Version: 1.0
Author URI: https://yourwebsite.com/
*/
<?php /** * @package Wbolt_shortcodes * @version 1.0 */ /* Plugin Name: Wbolt shortcodes Plugin URI: http://wordpress.org/extend/plugins/# Description: This is an example plugin Author: Your Name Version: 1.0 Author URI: https://yourwebsite.com/ */
<?php
/**
* @package Wbolt_shortcodes
* @version 1.0
*/
/*
Plugin Name: Wbolt shortcodes
Plugin URI: http://wordpress.org/extend/plugins/#
Description: This is an example plugin 
Author: Your Name
Version: 1.0
Author URI: https://yourwebsite.com/
*/

現在我們有了一個全新的外掛,但它仍然什麼也沒做。瀏覽到WordPress儀表盤中的外掛管理螢幕並啟用新外掛,確保您已在wp-config.php檔案中將WP_DEBUG設定為true

您的沙盒現在已準備好進行黑客攻擊。下一步是為自定義簡碼註冊一個鉤子:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
/**
* Add a hook for a shortcode tag
*/
function wbolt_shortcodes_init(){
add_shortcode( 'wbolt_get_posts', 'wbolt_get_posts_cb' );
}
add_action('init', 'wbolt_shortcodes_init');
/** * Add a hook for a shortcode tag */ function wbolt_shortcodes_init(){ add_shortcode( 'wbolt_get_posts', 'wbolt_get_posts_cb' ); } add_action('init', 'wbolt_shortcodes_init');
/**
* Add a hook for a shortcode tag
*/
function wbolt_shortcodes_init(){
add_shortcode( 'wbolt_get_posts', 'wbolt_get_posts_cb' );
}
add_action('init', 'wbolt_shortcodes_init');

wbolt_get_posts是短程式碼名稱,wbolt_get_posts_cb是下面定義的回撥:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
/**
* Register a shortcode
*
* @param array $atts Array of shortcode attributes
*/
function wbolt_get_posts_cb( $atts ){
// safely extract custom arguments and set default values
extract( shortcode_atts(
array(
'numberposts' => 3,
'post_type' => 'post',
'book_category' => 'fantasy',
'year_published' => 1900,
'price_min' => 0,
'price_max' => 50
),
$atts,
'wbolt_get_posts'
) );
// define the array of query arguments
$args = array(
'numberposts' => $numberposts,
'post_type' => $post_type,
'tax_query' => array(
array(
'taxonomy' => 'book_category',
'field' => 'slug',
'terms' => $book_category,
)
),
'meta_query' => array(
'relation' => 'AND',
'year_clause' => array(
'key' => 'year_published',
'value' => $year_published,
'type' => 'numeric',
'compare' => '>',
),
'price_clause' => array(
'key' => 'price',
'value' => array( $price_min, $price_max ),
'type' => 'numeric',
'compare' => 'BETWEEN',
)
),
'orderby' => array( 'price_clause' => 'ASC' )
);
$custom_posts = get_posts( $args );
if( ! empty( $custom_posts ) ){
$output = '<ul>';
foreach ( $custom_posts as $p ){
$output .= '<li><a href="'
. get_permalink( $p->ID ) . '">'
. $p->post_title . '</a> ('
. get_post_meta( $p->ID, 'year_published', true )
. ') - Price: ' . get_post_meta( $p->ID, 'price', true ) . '</li>';
}
$output .= '</ul>';
}
return $output ?? '<strong>Sorry. No posts matching your criteria!</strong>';
/** * Register a shortcode * * @param array $atts Array of shortcode attributes */ function wbolt_get_posts_cb( $atts ){ // safely extract custom arguments and set default values extract( shortcode_atts( array( 'numberposts' => 3, 'post_type' => 'post', 'book_category' => 'fantasy', 'year_published' => 1900, 'price_min' => 0, 'price_max' => 50 ), $atts, 'wbolt_get_posts' ) ); // define the array of query arguments $args = array( 'numberposts' => $numberposts, 'post_type' => $post_type, 'tax_query' => array( array( 'taxonomy' => 'book_category', 'field' => 'slug', 'terms' => $book_category, ) ), 'meta_query' => array( 'relation' => 'AND', 'year_clause' => array( 'key' => 'year_published', 'value' => $year_published, 'type' => 'numeric', 'compare' => '>', ), 'price_clause' => array( 'key' => 'price', 'value' => array( $price_min, $price_max ), 'type' => 'numeric', 'compare' => 'BETWEEN', ) ), 'orderby' => array( 'price_clause' => 'ASC' ) ); $custom_posts = get_posts( $args ); if( ! empty( $custom_posts ) ){ $output = '<ul>'; foreach ( $custom_posts as $p ){ $output .= '<li><a href="' . get_permalink( $p->ID ) . '">' . $p->post_title . '</a> (' . get_post_meta( $p->ID, 'year_published', true ) . ') - Price: ' . get_post_meta( $p->ID, 'price', true ) . '</li>'; } $output .= '</ul>'; } return $output ?? '<strong>Sorry. No posts matching your criteria!</strong>';
/**
* Register a shortcode
*
* @param array $atts Array of shortcode attributes
*/
function wbolt_get_posts_cb( $atts ){
// safely extract custom arguments and set default values
extract( shortcode_atts(
array(
'numberposts'		=> 3,
'post_type'			=> 'post',
'book_category'		=> 'fantasy',
'year_published'	=> 1900,
'price_min'			=> 0,
'price_max'			=> 50
),
$atts,
'wbolt_get_posts'
) );
// define the array of query arguments
$args = array(
'numberposts'	=> $numberposts,
'post_type'		=> $post_type,
'tax_query'		=> array(
array(
'taxonomy'	=> 'book_category',
'field'		=> 'slug',
'terms'		=> $book_category,
)
),
'meta_query'	=> array(
'relation'		=> 'AND',
'year_clause'	=> array(
'key'		=> 'year_published',
'value'		=> $year_published,
'type'		=> 'numeric',
'compare'	=> '>',
),
'price_clause'	=> array(
'key'		=> 'price',
'value'		=> array( $price_min, $price_max ),
'type'		=> 'numeric',
'compare'	=> 'BETWEEN',
)
),
'orderby' => array( 'price_clause' => 'ASC' )
);
$custom_posts = get_posts( $args );
if( ! empty( $custom_posts ) ){
$output = '<ul>';
foreach ( $custom_posts as $p ){
$output .= '<li><a href="' 
. get_permalink( $p->ID ) . '">' 
. $p->post_title . '</a> (' 
. get_post_meta( $p->ID, 'year_published', true ) 
. ') - Price: ' . get_post_meta( $p->ID, 'price', true ) . '</li>';
}
$output .= '</ul>';
}
return $output ?? '<strong>Sorry. No posts matching your criteria!</strong>';

我們設定了六個用於定義引數陣列的簡碼屬性,最終將其傳遞給WordPressget_posts函式。如果$custom_posts不為空,則foreach迴圈生成專案無序列表的HTML。

現在您和您部落格的作者可以使用如下短程式碼包含文章列表:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
[wbolt_get_posts post_type="book" book_category="sci-fi" numberposts="4" price_min=1 price_max=250]
[wbolt_get_posts post_type="book" book_category="sci-fi" numberposts="4" price_min=1 price_max=250]
[wbolt_get_posts post_type="book" book_category="sci-fi" numberposts="4" price_min=1 price_max=250]

當然,您可以根據需要更改引數陣列,並在開發網站的任何文章或頁面中執行測試。

使用get_posts函式構建的高階文章列表

使用get_posts函式構建的高階文章列表

小計

WordPress的get_posts是一個強大的函式,它允許開發人員在您的WordPress網站前端的任何位置包含文章列表。它使用WP_Query但更易於使用,並且比WP_Query您只需要文章列表時更可取。WP_Query無論如何,當您需要在Loop中顯示文章時,建議直接引用。

因此,構建您的列表,測試您的程式碼,當您確定它工作正常時,然後(並且只有在那時)將其推送到您的實時網站(但首先執行備份)。

評論留言