2012-02-08 16 views
2

例:Wordpressの親ページタイトルでページのすべての子ページを取得するには?

About 
--- technical 
--- medical 
--- historical 
--- geographical 
--- political 

がどのようにこのような関数を作成するには?

function get_child_pages_by_parent_title($title) 
{ 
    // the code goes here 
} 

このように呼び出すと、オブジェクトがいっぱいの配列が返されます。あなたがこれを使用することができます

$children = get_child_pages_by_parent_title('About'); 

答えて

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はより安定しています。オプションの第2引数として返されるページの制限を実装してください。 –

+0

が修正されました(tnkxの場合はこれを上書きできます) – janw

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

関連する問題