問題描述
有沒有辦法可以從以下內容中檢索一組查詢的帖子 ID?
$latest = new WP_Query( array (
'orderby' => 'rand',
'posts_per_page' => 3
));
if ( $latest -> have_posts() ) : while ( $latest -> have_posts() ) : $latest -> the_post();
get_template_part( 'templates/content', 'post' );
endwhile; endif; wp_reset_postdata();
跟進:
我使用 wp_list_pluck
來檢索一個 post id 陣列:
$post_ids = wp_list_pluck( $latest->posts, 'ID' );
然後使用 implode 函式將陣列轉換成字串:
$post_ids_string = implode( ',', $post_ids );
對不起,這個模糊的問題。
最佳解決方案
嘗試
$post_ids = wp_list_pluck( $latest->posts, 'ID' );
閱讀 wp_list_pluck
次佳解決方案
在查詢中使用 fields
引數。
fields (string) – Which fields to return. All fields are returned by
default. There are two other options: – ‘ids’ – Return an array of post IDs. – ‘id=>parent’ – Return an associative array [ parent => ID, … ].http://codex.wordpress.org/Class_Reference/WP_Query#Return_Fields_Parameter
$latest = new WP_Query( array (
'orderby' => 'rand',
'posts_per_page' => 3,
'fields' => 'ids'
));
var_dump($latest->posts);
參考文獻
注:本文內容整合自 Google/Baidu/Bing 輔助翻譯的英文資料結果。如果您對結果不滿意,可以加入我們改善翻譯效果:薇曉朵技術論壇。