問題描述
當使用 WP_Query 方法執行查詢時,我得到一個物件。我明白我可以做迴圈顯示的東西。但是,我的目標不是顯示任何東西,相反,我想透過做一些像”foreach…” 這樣的一些帖子資料。如何獲得一個可以迴圈並獲取資料的資料的資料?
最佳解決方案
您應該閱讀 WordPress 中的 function reference for WP_Query 。你有很多例子要看。如果您不想使用 while 迴圈使用結果集,則可以使用 posts 中的 WP_Query 獲取查詢返回的所有帖子。
例如
$query = new WP_Query( array( 'post_type' => 'page' ) );
$posts = $query->posts;
foreach($posts as $post) {
// Do your stuff, e.g.
// echo $post->post_name;
}
次佳解決方案
其實你不需要拒絕使用 while()迴圈。相同的 WP_Post 物件已經儲存在 post 屬性中:
$query = new WP_Query( $args );
if ( $query->have_posts() ) {
while ( $query->have_posts() ) {
$query->the_post();
// now $query->post is WP_Post Object, use:
// $query->post->ID, $query->post->post_title, etc.
}
}
參考文獻
注:本文內容整合自 Google/Baidu/Bing 輔助翻譯的英文資料結果。如果您對結果不滿意,可以加入我們改善翻譯效果:薇曉朵技術論壇。