WordPress 列出搜索结果中的自定义分类术语



我创建了一个名为"项目"的自定义帖子类型,其中包含自定义分类法。我创建了多个项目,并使用称为"公司"的自定义分类法标记了这些项目。

我想做的是,当我搜索一个被标记为多个"公司"的项目时,在搜索结果页面上有一个名为"公司"的部分,只列出公司。

我目前所拥有的是,当我搜索并显示多个项目时,它会复制"公司"分类法,但我只想显示一个分类法并删除任何重复项。

我现在的代码是:

<?php                   
  // the query
  $search_query = new WP_Query( $args ); ?>
  <?php if ( $search_query->have_posts() ) : ?>
    <ul class="search-result">
      <!-- pagination here -->
        <!-- the loop -->
        <?php while ( $search_query->have_posts() ) : $search_query->the_post(); ?>
        <li>
          <?php echo get_the_term_list( $post->postname, 'companies', 'Disipline: ', ', ' ); ?>
        </li>
        <?php endwhile; ?>
        <!-- end of the loop -->
        <!-- pagination here -->
    </ul>
    <?php wp_reset_postdata(); ?>
    <?php else : ?>
      <p><?php esc_html_e( 'Sorry, no posts matched your criteria.' ); ?></p>
    <?php endif; ?>

如果我有 2 个项目的搜索结果,我会得到 2 个术语列表,即电影、视频、电影......但我只想说电影,视频

我设法解决了我的问题,所以发布了我的答案。

<div class="search-container">
  <h2 class="pagetitle">In: <span>Discipline</span></h2>
    <ul class="search-result">
      <?php
        $_terms = get_terms( array('sectors') );
        foreach ($_terms as $term) :
        $term_slug = $term->slug;
        $term_link = get_term_link( $term );
        $_posts = new WP_Query( array(
          'post_type'         => 'projects',
          's'                 => $s,
          'posts_per_page'    => 10, //important for a PHP memory limit warning
          'tax_query' => array(
            array(
              'taxonomy' => 'sectors',
              'field'    => 'slug',
              'terms'    => $term_slug,
            ),
        ),
    ));
    if( $_posts->have_posts() ) :
      echo '<li>'. '<h3>' . $term->name . '</h3>';
      echo '<p>' . $term->description . '</p>';
      // We successfully got a link. Print it out.
      echo '<a href="' . esc_url( $term_link ) . '">' . 'view page' .         '</a></li>';
    ?>
    <?php
      endif;
        wp_reset_postdata();
        endforeach;
    ?>
   </ul>
</div>

最新更新