使用 WP_Query 显示所有带有自定义分类的帖子

Displaying all posts with custom taxonomy using WP_Query

我正在尝试显示具有自定义分类法的自定义 post 类型,但我没有任何运气。什么都没有出现。感谢您的帮助。

Post类型=大学

自定义分类 slug = 国家

我想使用 WP_Query 显示所有国家/地区列表,因为此分类法中有一些自定义字段。此外,点击任何国家/地区时,它应该重定向到包含其详细信息的国家/地区页面

下面是我的代码

<?php
      $args = array(
        'post_type' => 'university',
        'tax_query' => array(
             array(
                 'taxonomy' => 'country'
             )
         )
      );

     $query = new WP_Query($args);

     if ($query->have_posts()) {
        while ($query->have_posts()) {
           $query->the_post();
     ?>

              <a title="<?php the_title(); ?>"> 

                 <h3><?php the_title(); ?></h3>

              </a>
     <?php
        }
     }
     wp_reset_postdata();
    ?>

我已经修改了你的代码,请试试看。

<?php

      $custom_terms = get_terms('country');
      $args = array(
        'post_type' => 'university',
        'tax_query' => array(             
             array(
                'taxonomy' => 'country',
                'field' => 'slug',
                'terms' => $custom_terms[0]->slug, // or the category name e.g. Germany
            ),
         )
      );

     $query = new WP_Query($args);

     if ($query->have_posts()) {
        while ($query->have_posts()) {
           $query->the_post();
     ?>

              <a title="<?php the_title(); ?>"> 

                 <h3><?php the_title(); ?></h3>

              </a>
     <?php
        }
     }
     wp_reset_postdata();
    ?>

我们获取分类法的所有术语,遍历它们,并为属于该术语的每个 post 触发标题 link。