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

WordPress自定义分类法标签查询关联文章及手风琴展示实现求助

解决思路与完整实现

PHP循环逻辑

你需要在遍历chef自定义分类法术语的循环中,追加关联文章的查询逻辑,替换原有代码的完整可运行代码如下:

<!-- 替换你原有代码的完整PHP逻辑 -->
<ul id="chef-accordion" class="chef-accordion">
  <?php
  // 获取chef分类法下所有有文章的标签
  $terms = get_terms( array(
    'taxonomy'   => 'chef',
    'hide_empty' => true, // 只展示有绑定文章的标签,不需要可以改回false
    'orderby'    => 'name',
    'order'      => 'ASC'
  ) );

  if ( ! empty( $terms ) && is_array( $terms ) ) :
    foreach ( $terms as $term ) :
      // 查询当前标签绑定的所有文章
      $post_query = new WP_Query( array(
        'post_type'      => 'post', // 若为自定义文章类型请修改对应值
        'posts_per_page' => -1,
        'post_status'    => 'publish',
        'orderby'        => 'date',
        'order'          => 'DESC', // 最新文章在前,要旧文在前改ASC
        'tax_query'      => array(
          array(
            'taxonomy' => 'chef',
            'field'    => 'term_id',
            'terms'    => $term->term_id,
          )
        )
      ) );

      if ( $post_query->have_posts() ) :
  ?>
    <li class="chef-accordion-item">
      <h3 class="chef-term-title"><?php echo esc_html( $term->name ); ?></h3>
      <ul class="chef-article-list">
        <?php while ( $post_query->have_posts() ) : $post_query->the_post(); ?>
        <li>
          《<?php echo esc_html( get_the_title() ); ?>》 
          <?php echo get_the_date( 'd/m/Y' ); ?>
        </li>
        <?php endwhile; ?>
      </ul>
    </li>
  <?php
      wp_reset_postdata(); // 重置文章查询,避免影响页面主逻辑
      endif;
    endforeach;
  endif;
  ?>
</ul>

如果需要保留原有跳转到标签归档页的功能,可把<h3 class="chef-term-title">替换为:

<a href="<?php echo esc_url( get_term_link( $term ) ); ?>" class="chef-term-title"><?php echo esc_html( $term->name ); ?></a>

手风琴效果实现

无需引入第三方库,追加以下CSS和JS代码即可实现点击展开/折叠效果:

/* 加入到主题自定义CSS中即可 */
.chef-accordion-item .chef-article-list {
  display: none;
  margin: 8px 0 16px 24px;
  list-style: disc;
}
.chef-accordion-item.active .chef-article-list {
  display: block;
}
.chef-term-title {
  cursor: pointer;
  margin: 12px 0;
  padding: 6px 8px;
  background: #f5f5f5;
  border-radius: 4px;
}
// 加入到主题页脚自定义JS中即可
document.addEventListener('DOMContentLoaded', function() {
  const accordionTitles = document.querySelectorAll('.chef-term-title');
  accordionTitles.forEach(title => {
    title.addEventListener('click', function(e) {
      // 如果用了a标签跳转,要保留跳转功能就删掉下面这行
      e.preventDefault();
      this.parentElement.classList.toggle('active');
    });
  });
});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 03:06:02