如何基于WordPress查询构建二维数组生成分组套餐HTML内容
按章节分组展示WordPress套餐的实现方案
1. 构建按章节分组的二维数组
先通过WordPress查询获取所有套餐,按章节(自定义分类/自定义字段)分组生成二维数组:
// 初始化分组数组 $grouped_packages = []; // 查询套餐自定义文章类型(替换为你的实际文章类型slug) $package_query = new WP_Query([ 'post_type' => 'package', 'posts_per_page' => -1, 'order' => 'ASC', 'orderby' => 'title' ]); if ($package_query->have_posts()) { while ($package_query->have_posts()) { $package_query->the_post(); // 获取章节标题:这里用自定义分类法示例,若用自定义字段则替换为get_post_meta $sections = get_the_terms(get_the_ID(), 'package_section'); // 替换为你的分类法slug if ($sections && !is_wp_error($sections)) { $section_title = $sections[0]->name; // 将套餐数据存入对应章节的数组 $grouped_packages[$section_title][] = [ 'id' => get_the_ID(), 'title' => get_the_title() ]; } } wp_reset_postdata(); }
2. 修改模板代码,按分组渲染
把原模板的单层循环改成嵌套循环,先渲染章节标题,再输出对应套餐:
<section id="packages" data-aos-delay="0" data-aos-duration="0" data-aos="fade" class="page-section"> <div class="pricing-header px-3 py-3 pt-md-5 pb-md-4 mx-auto text-center"> <h1 class="display-4" data-aos="zoom-out-up">Packages</h1> </div> <div class="container"> <!-- 遍历每个章节 --> <?php foreach ($grouped_packages as $section_title => $packages) : ?> <!-- 章节标题 --> <div class="row justify-content-center mb-4"> <div class="col-12 text-center"> <h2 class="h3 fw-bold"><?php echo esc_html($section_title); ?></h2> </div> </div> <!-- 章节下的套餐列表 --> <div class="row justify-content-center mb-3"> <?php foreach ($packages as $package) : ?> <?php $title = $package['title']; $package_price = get_post_meta($package['id'], '_package_price', true); $package_subtitle = get_post_meta($package['id'], '_package_subtitle', true); $package_attributes = get_post_meta($package['id'], "_package_attributes", true); ?> <div class="col-lg-4 col-md-4 col-sm-12"> <div class="card mb-4 box-shadow"> <div class="card-header"> <h2 class="my-3">$ <?php echo esc_html($package_price); ?></h2> <h4 class="my-1"><?php echo esc_html($title); ?></h4> <h6 class="mb-2"><?php echo esc_html($package_subtitle); ?></h6> </div> <div class="card-body"> <ul class="list-unstyled"> <?php if (is_array($package_attributes)) : ?> <?php foreach ($package_attributes as $attribute) : ?> <li><?php echo esc_html($attribute); ?></li> <?php endforeach; ?> <?php endif; ?> </ul> <a href="#contactUs" type="button" class="btn btn-lg btn-block btn-primary">Enquire</a> </div> </div> </div> <?php endforeach; ?> </div> <?php endforeach; ?> </div> </section>
注意事项
- 章节标识:如果不用自定义分类,而是用自定义字段存储章节名称,把获取分类的代码改成
$section_title = get_post_meta(get_the_ID(), '_package_section', true);即可 - 安全输出:所有动态内容用
esc_html()转义,避免XSS安全风险 - 样式调整:章节标题的样式可以通过修改类名或添加自定义CSS适配你的设计
内容的提问来源于stack exchange,提问作者newbie dev
相关产品推荐
相关产品推荐

