首页 > 解决方案 > Wordpress 短代码按父母 ID 显示所有子页面

问题描述

我正在编写一个通过父 ID 循环并显示所有子页面的短代码,但我不太确定如何制作循环并使其更加自定义。

这是我的代码: add_shortcode( 'home-page-listing', 'get_list' );

function get_list( $atts ) {
    ob_start();
    $atts = shortcode_atts( array(
            'ids' => ''
    ), $atts );
    if($atts['ids']!='')
    {
        $id_array = explode(',',$atts['ids']);
        $homePages = new WP_Query( array(
                'post_type' => 'page',
                'post__in'=>$id_array,
                'order' => 'ASC',
                'orderby' => 'post__in',
                'posts_per_page' => -1
        ) );
        if ($homePages->have_posts()){?>
            <div class="">

                <?php while ( $homePages->have_posts() ) : $homePages->the_post(); ?>
                     //here's html template code
                <?php endwhile;
                wp_reset_postdata(); ?>
            </div>
        }
    }
}

现在我可以[home-page-listing id=1,2,3,4]用来显示所有选择页面 ID,但我想这样:

[home-page-listing parentID=4]

循环遍历所有子页面并显示到字体,而不是检查所有要显示的页面 id。

谢谢!

标签: phpwordpressloopsshortcode

解决方案


它的简单使用post_parent参数 WP_Query。请检查以下示例

$homePages = new WP_Query( array(
    'post_type' => 'page',
    'post_parent'=>$parentID,
    'order' => 'ASC',
    'orderby' => 'parent',
    'posts_per_page' => -1
) );

有关 WP_Query 的更多信息,请单击此处


推荐阅读