You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

WordPress实现任意页面通过短代码显示指定父页面子页面

实现任意页面调用指定父页面子页面的短代码

完全可行!不过我更推荐用参数传递的方式来实现,比你说的[wpb_childpages_xxx]后缀形式更灵活——不需要为每个父页面单独注册短代码,一个短代码就能适配所有场景。下面是具体的实现方案:

完整代码实现

把这段代码添加到你的主题functions.php文件,或者使用自定义代码插件(比如Code Snippets)来添加:

function wpb_childpages_shortcode($atts) {
    // 设置短代码默认参数
    $atts = shortcode_atts(
        array(
            'parent' => '', // 接收父页面标识:ID、slug或标题
        ),
        $atts,
        'wpb_childpages'
    );

    // 处理父页面标识,转换成页面ID
    $parent_id = 0;
    if (!empty($atts['parent'])) {
        if (is_numeric($atts['parent'])) {
            // 如果是数字,直接作为页面ID
            $parent_id = intval($atts['parent']);
        } else {
            // 先尝试通过slug获取页面
            $parent_page = get_page_by_path($atts['parent']);
            if (!$parent_page) {
                // slug不存在的话,尝试通过标题获取
                $parent_page = get_page_by_title($atts['parent']);
            }
            if ($parent_page) {
                $parent_id = $parent_page->ID;
            }
        }
    }

    // 没有有效父页面ID时返回提示
    if ($parent_id === 0) {
        return '<p>请指定有效的父页面标识(页面ID、slug或标题)</p>';
    }

    // 查询父页面的所有子页面
    $child_pages_query = new WP_Query(array(
        'post_type' => 'page',
        'post_parent' => $parent_id,
        'posts_per_page' => -1, // 显示所有子页面
        'orderby' => 'menu_order', // 按后台设置的菜单顺序排序
        'order' => 'ASC',
        'post_status' => 'publish' // 只显示已发布的页面
    ));

    // 生成子页面列表
    if ($child_pages_query->have_posts()) {
        $output = '<ul class="custom-child-pages">';
        while ($child_pages_query->have_posts()) {
            $child_pages_query->the_post();
            $output .= sprintf(
                '<li><a href="%s">%s</a></li>',
                esc_url(get_permalink()),
                esc_html(get_the_title())
            );
        }
        $output .= '</ul>';
        // 重置WP查询,避免影响后续内容
        wp_reset_postdata();
        return $output;
    } else {
        return '<p>该父页面下没有已发布的子页面</p>';
    }
}
// 注册短代码
add_shortcode('wpb_childpages', 'wpb_childpages_shortcode');

怎么使用这个短代码?

你可以在任意页面(包括首页)使用以下三种方式调用:

  • 通过页面ID:[wpb_childpages parent="123"](把123替换成你的父页面ID)
  • 通过页面slug:[wpb_childpages parent="about-us"](about-us是父页面的URL别名)
  • 通过页面标题:[wpb_childpages parent="关于我们"](直接用父页面的标题)

自定义样式

如果需要调整列表的外观,只需要给.custom-child-pages类写CSS即可,比如:

.custom-child-pages {
    list-style: none;
    padding-left: 0;
}
.custom-child-pages li {
    margin-bottom: 8px;
}
.custom-child-pages a {
    color: #2c3e50;
    text-decoration: none;
}
.custom-child-pages a:hover {
    text-decoration: underline;
}

这个方案完美解决了你原来函数的局限性——不再局限于父页面内部调用,完全支持在任意页面指定任意父页面来展示子页面列表。

内容的提问来源于stack exchange,提问作者Joachim Tranberg

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 08:15:36