【问题标题】:Displaying all posts with custom taxonomy using WP_Query使用 WP_Query 显示具有自定义分类的所有帖子
【发布时间】:2018-03-09 03:15:53
【问题描述】:

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

帖子类型 = 大学

自定义分类 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 wordpress taxonomy


    【解决方案1】:

    我已经修改了你的代码,请尝试一下。

    <?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();
        ?>
    

    我们获取分类法的所有术语,遍历它们,然后为属于该术语的每个帖子触发标题链接。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-12-05
      • 1970-01-01
      相关资源
      最近更新 更多