get_page_children()不返回所有子页面

jor*_*dan 6 php wordpress

我在我的Wordpress主题中,我正在获取子页面以显示其信息.这就是我现在所拥有的:

<?php 
                $my_wp_query = new WP_Query();
                $all_wp_pages = $my_wp_query->query(array('post_type' => 'page'));

                $staff = get_page_children(8, $all_wp_pages);

                foreach($staff as $s){
                    $page = $s->ID;
                    $page_data = get_page($page);
                    $content = $page_data->post_content;
                    $content = apply_filters('the_content',$content);
                    $content = str_replace(']]>', ']]>', $content);
                    echo '<div class="row-fluid"><span class="span4">'; 
                    echo get_the_post_thumbnail( $page ); 
                    echo '</span><span class="span8">'.$content.'</span></div>';
                } 
        ?>
Run Code Online (Sandbox Code Playgroud)

我有五个应该出现的子页面,但只有三个正在返回.我在$ staff上使用print_r来查看其他页面是否在数组中,但它们不是.我不确定问题是什么.

小智 24

get_page_children()或者没有任何问题new WP_Query().默认情况下,WP_Query仅返回x创建的最后页数.这是强加的限制WP_Query.

get_page_children()只需获取返回的pages数组WP_Query并过滤该列表中的子页面.根据WordPress Codex:get_page_children"...不会进行任何SQL查询来获取孩子."

要解决此问题,只需使用:

    $query = new WP_Query( 'posts_per_page=-1' );
Run Code Online (Sandbox Code Playgroud)

您修复的代码:

    <?php 
    $my_wp_query = new WP_Query();
    $all_wp_pages = $my_wp_query->query(array('post_type' => 'page', 'posts_per_page' => -1));

    $staff = get_page_children(8, $all_wp_pages);

    foreach($staff as $s){
        $page = $s->ID;
        $page_data = get_page($page);
        $content = $page_data->post_content;
        $content = apply_filters('the_content',$content);
        $content = str_replace(']]>', ']]>', $content);
        echo '<div class="row-fluid"><span class="span4">'; 
        echo get_the_post_thumbnail( $page ); 
        echo '</span><span class="span8">'.$content.'</span></div>';
    } 
    ?>
Run Code Online (Sandbox Code Playgroud)

这是一个帮助函数,您可以在需要获取页面子项时调用它

    function my_get_page_children( $page_id, $post_type = 'page' ) {
        // Set up the objects needed
        $custom_wp_query = new WP_Query();
        $all_wp_pages    = $custom_wp_query->query( array( 'post_type' => $post_type, 'posts_per_page' => -1 ) );

        // Filter through all pages and find specified page's children
        $page_children = get_page_children( $page_id, $all_wp_pages );

        return $page_children;
    }
Run Code Online (Sandbox Code Playgroud)

您使用辅助函数进行编码

    foreach(my_get_page_children(8) as $s){
        $page = $s->ID;
        $page_data = get_page($page);
        $content = $page_data->post_content;
        $content = apply_filters('the_content',$content);
        $content = str_replace(']]>', ']]>', $content);
        echo '<div class="row-fluid"><span class="span4">'; 
        echo get_the_post_thumbnail( $page ); 
        echo '</span><span class="span8">'.$content.'</span></div>';
    } 
Run Code Online (Sandbox Code Playgroud)