在 WordPress 中,可以通過分類或者標簽的形式聚合文章,如果你想要通過自定義字段來聚合,也未嘗不可。這篇文章會告訴你如何按自定義字段獲取 WordPress 文章列表。你有可能會在 WordPress 自定義頁面模板中用到它。
<?php// The Query to show a specific Custom Field$the_query = new WP_Query('meta_key=color');// The Loopwhile ( $the_query->have_posts() ) : $the_query->the_post();the_title();the_content();endwhile;// Reset Post Datawp_reset_postdata();?>
現在如果你想要按某個特定值的自定義字段獲取文章列表,只要改變以下代碼中的查詢條件參數即可:
$the_query = new WP_Query( 'meta_value=blue' );
現在,如果你想分別按照自定義字段名稱和取值來獲取文章列表,比如獲取所有自定義字段名稱為“color”,并且值為“blue”的文章,你可以這么來搞:
$the_query = new WP_Query( array( 'meta_key' => 'color', 'meta_value' => 'blue' ) );
通過自定義字段可以將 WordPress 擴展出很多實用的功能,詳細可以參考官方文檔關于 WP_Query Parameters 的介紹。