2012-02-08 71 views

回答

9

你可以使用這個,但它在頁面ID的工作而不是標題,如果你真的需要頁面的標題,我可以修復它,但ID爲更穩定。

<?php 
function get_child_pages_by_parent_title($pageId,$limit = -1) 
{ 
    // needed to use $post 
    global $post; 
    // used to store the result 
    $pages = array(); 

    // What to select 
    $args = array(
     'post_type' => 'page', 
     'post_parent' => $pageId, 
     'posts_per_page' => $limit 
    ); 
    $the_query = new WP_Query($args); 

    while ($the_query->have_posts()) { 
     $the_query->the_post(); 
     $pages[] = $post; 
    } 
    wp_reset_postdata(); 
    return $pages; 
} 
$result = get_child_pages_by_parent_title(12); 
?> 

這一切都記錄在這裏:
http://codex.wordpress.org/Class_Reference/WP_Query

+0

感謝您使用此快速代碼。是的,我同意你的ID更穩定。作爲可選的第二個參數,您能否實現返回頁面的限制? – 2012-02-08 14:32:57

+0

固定(可以upvote這爲tnkx) – janw 2012-02-08 15:11:07

8

我寧願不WP_Query這樣做。雖然它可能不是更有效率,但至少你可以節省一些時間,而不必再一次編寫/ have_posts()/ the_post()語句中的所有內容。

function page_children($parent_id, $limit = -1) { 
    return get_posts(array(
     'post_type' => 'page', 
     'post_parent' => $parent_id, 
     'posts_per_page' => $limit 
    )); 
} 
5

爲什麼不使用get_children()? (一旦它被認爲使用ID而不是標題)

$posts = get_children(array(
    'post_parent' => $post->ID, 
    'post_type' => 'page', 
    'post_status' => 'publish', 
)); 

檢查the official documentation

相關問題