首页 > 解决方案 > 如何查询自定义帖子类型分类以创建模板页面的分类列表

问题描述

我正在尝试构建archive-custom.php 页面以显示选项卡式列表。每个自定义帖子类型都是与分类相关的“消息”,该分类将它们分组并组织成“系列”。分类法包含有关每个系列的信息,包括它的“系列类型”和每个系列的图形。

目标是页面显示所有“main”类型的“系列”列表,并带有图形和分类名称。单击“系列”将带您进入该“系列”页面,其中包含所有“消息”的列表

我得到了一个查询来返回我想要的大部分信息,此时它只返回重复项,因为我的查询是错误的。它为每个“消息”返回“系列”,所以如果有 4 条“消息”,我会收到 4 次“系列”。我知道查询需要更改。

我在返回分类名称时也遇到了问题。在下面的代码中,我让它返回 2 种不同的方式 - 一种有效,但在链接中返回分类名称,这是不必要的。另一个只是返回“数组”,因为我的语法错误,而且我在 Wordpress 法典中找不到示例。

我对 Wordpress 查询不是很熟悉,但我觉得这里有一个不必要的重复查询。

<?php       
   //this initial query is returning the results for each message instead of returning just each series in the type "main"  
   $args = array(
      'post_type'   => 'messages',
      'post_status' => 'publish',
      //thanks to dmarco for pointing out this should use the meta_query instead
      //not certain how to meta_query the attached taxonomy
      'tax_query'   => array(
         array(
        'taxonomy' => 'cpt_series',
        'field'    => 'series_type',
        'terms'    => 'main'
         )
      )
   );


   $series = new WP_Query( $args );
   if( $series->have_posts() ) :
?>
      <ul>
<?php
      while( $series->have_posts() ) :
         $series->the_post();

         //get the custom taxonomy fields and assign them to var
         //this query is to access the custom post type fields.
         $types = get_terms( array(
            'taxonomy' => 'cpt_series',
            'hide_empty' => true,
         ));

         foreach($types as $type) {
            $image = get_field('series_graphic', 'cpt_series_' . $type->term_id . '' );
            $seriesLink = get_term_link($type->term_id, $taxonomy = 'cpt_series');
            //This title doesn't work - syntax is wrong
            $seriesTitle = wp_get_post_terms('name');

            if ( has_term( $type->term_id, 'cpt_series')) {
               $seriesGraphic = $image['url'];
            }
         }
?>

         <li>
            <a href="<?=$seriesLink?>">
<?php 
               echo '<img src="' . $seriesGraphic . '" />';
               echo $seriesTitle;
               $seriesTitle = the_terms($post->ID, 'sermon_series', '');
?>
            </a>
         </li>
<?php
      endwhile;
      wp_reset_postdata();
?>
      </ul>
<?php
   else :
      esc_html_e( 'No series available!', 'text-domain' );
   endif;           
?>

它非常接近于做我想做的事,再次只是为每个“消息”获取“系列”,而不仅仅是“main”类型中所有“系列”的列表。也很想知道如何正确返回“名称”。谢谢。

标签: phpwordpress

解决方案


对于您遇到的第一个问题:

$args = array(
    'post_type'   => 'messages',
    'post_status' => 'publish',
    'tax_query'   => array(
        array(
            'taxonomy' => 'cpt_series',
            'field'    => 'series_type',
            'terms'    => 'main'
        )
    )
);

'field' => 'series_type'- 您在此处按您搜索的内容命名,选项为 :term_id、、或。转到数据库并找到表 wp_terms。在那里您可能会看到这些值。所以我假设这些行应该看起来像:nameslugterm_taxonomy_id

array(
    'taxonomy' => 'cpt_series',
    'field'    => 'slug',
    'terms'    => 'main'
)

推荐阅读