如何列出自定义帖子类型(分类法)中的所有帖子

时间:2019-08-26 11:03:01

标签: php wordpress

我正在尝试显示分类法中的所有帖子。我有帖子类型(文档)和分类法(type_docs),我试图列出该帖子类型中的所有帖子。我的代码是这样的,但是不起作用

<?php
  $custom_terms = get_terms('type_docs');

 foreach($custom_terms as $custom_term) {
   wp_reset_query();
    $args = array('post_type' => 'docs',
    'tax_query' => array(
        array(
            'taxonomy' => 'type_docs',
            'field' => 'slug',
            'terms' => $custom_term->slug,
        ),
    ),
 );

 $loop = new WP_Query($args);
 if($loop->have_posts()) {
    echo '<h2>'.$custom_term->name.'</h2>';

    while($loop->have_posts()) : $loop->the_post();
        echo '<a href="'.get_permalink().'">'.get_the_title().'</a> 
 <br>';
    endwhile;
   }
}
?>

我正在尝试仅列出分类法中的所有帖子,有人可以帮忙吗?

1 个答案:

答案 0 :(得分:0)

我不知道您为什么要这样做,但这是解决方案:

<?php

// Get your custom terms
$custom_terms = get_terms('type_docs');

// Prepare the query
$args = array(
  'post_type' => 'docs',
  'posts_per_page' => -1,
  'tax_query' => array()
);

// Prepare the array to receive terms tax_query
$terms_query = array();

foreach($custom_terms as $custom_term) {

  // Add terms to the tax query
  $args['tax_query'][] = array(
      'taxonomy' => 'type_docs',
      'field' => 'slug',
      'terms' => $custom_term->slug,
  );
}

// Get the posts (or you could do your new WP_Query)
$posts = get_posts($args);

// Display
foreach($posts as $post) : setup_postdata($post); ?>

  <a href="<?php the_permalink(); ?>"><?php the_title(); ?></a><br>

<?php endforeach; ?>
相关问题