問題描述
我需要得到一個特定 (根) 父 ID 的所有 sub-posts 。
get_posts( array( 'numberposts' => -1, 'post_status' => 'publish', 'post_type' => 'microsite', 'post_parent' => $root_parent_id, 'suppress_filters' => false ) );
WP-Codex:get_post()函數具有 post_parent,但沒有 child_of 參數。
函數 get_pages() 與 child_of 參數的組合的優點是 「… 請注意,child_of 參數還將獲取給定 ID 的”grandchildren”,而不僅僅是直接後代。」*
最佳解決方案
您將需要循環使用這些帖子,然後對每個帖子進行更多查詢,重複,直到您在查詢中找不到任何帖子。
例如
function get_posts_children($parent_id){
$children = array();
// grab the posts children
$posts = get_posts( array( 'numberposts' => -1, 'post_status' => 'publish', 'post_type' => 'microsite', 'post_parent' => $parent_id, 'suppress_filters' => false ));
// now grab the grand children
foreach( $posts as $child ){
// recursion!! hurrah
$gchildren = get_posts_children($child->ID);
// merge the grand children into the children array
if( !empty($gchildren) ) {
$children = array_merge($children, $gchildren);
}
}
// merge in the direct descendants we found earlier
$children = array_merge($children,$posts);
return $children;
}
// example of using above, lets call it and print out the results
$descendants = get_posts_children($post->ID);
echo '<pre>';
print_r($descendants);
echo '</pre>';
上面的函數是自己調用的,它是一個遞歸函數。它將繼續調用自己,直到它到達一個點,看着的帖子沒有孩子,那麼它將返回而不調用自己,整個堆棧將回彈建立一個孩子的數組。你會在這方面做進一步的研究。
請注意,無論您使用遞歸函數還是使用遞歸函數,都有固有的成本,這與您所擁有的帖子數量有關。 5 級職位的成本要高於 2 級,而不是線性縮放。您可能需要使用瞬態來緩存輸出,具體取決於您的操作。
降低成本的另一種方法是通過僅查看一定數量的級別的帖子樹。孫子,但沒有孫子孫子。這可以通過傳入深度參數,並在每次遞歸調用時遞減,確保在深度為 0 或更低時在開始時返回一個空數組。關於遞歸函數的許多教程都以此為例。
參考文獻
注:本文內容整合自 Google/Baidu/Bing 輔助翻譯的英文資料結果。如果您對結果不滿意,可以加入我們改善翻譯效果:薇曉朵技術論壇。