admin管理员组

文章数量:1312658

I am trying to make a list of all my posts in a custom post type by the taxonomy term e.g.

Term name 1 - post 1 - post 2 - post 3

Term name 2 - post 1 - post 2 - post 3

Term name 3 - post 1 - post 2 - post 3

I have found the function which lists the terms (get_terms) but can't work out a way to list the terms but also list the posts.

Any help is appreciated

I am trying to make a list of all my posts in a custom post type by the taxonomy term e.g.

Term name 1 - post 1 - post 2 - post 3

Term name 2 - post 1 - post 2 - post 3

Term name 3 - post 1 - post 2 - post 3

I have found the function which lists the terms (get_terms) but can't work out a way to list the terms but also list the posts.

Any help is appreciated

Share Improve this question asked May 8, 2014 at 9:51 Gareth GillmanGareth Gillman 1,3221 gold badge10 silver badges18 bronze badges 5
  • Not a lot to be honest, I am more looking for a pointer in the right direction on how to achieve it – Gareth Gillman Commented May 8, 2014 at 10:07
  • 1 You can get all the terms related to that post type and loop through them. Inside each loop, you can fetch the posts for that specific term. – Chittaranjan Commented May 8, 2014 at 10:46
  • I like your honesty @GarethGillman – Pieter Goosen Commented May 8, 2014 at 10:52
  • 1 Sorted, I was over thinking it and it was as simple as listing the terms (via get_terms) and in the foreach doing a separate query for the posts for that taxonomy. – Gareth Gillman Commented May 8, 2014 at 10:59
  • 1 To keep your question constructive and earn some reputation, please add your solution (code and a short description of the code) as an answer, and remember to come back in two days and accept your own answer. – Pieter Goosen Commented May 8, 2014 at 17:35
Add a comment  | 

2 Answers 2

Reset to default 1

Sorted via get_terms and WP_Query

<?php
  $terms = get_terms("county");
  if ( !empty( $terms ) && !is_wp_error( $terms ) ){
   foreach ( $terms as $term ) {
    $my_query = new WP_Query('post_type=venues&posts_per_page=-1&county='.$term->name);
    while ($my_query->have_posts()) : $my_query->the_post();
     echo '<h2>'.$term->name.'</h2>';
     echo '<ul>';
      echo '<li>'.get_the_title().'</li>';
      echo '<li>'.get_the_content().'</li>';
     echo '</ul>';
    endwhile; wp_reset_query();
   }
  }
  ?>

I first get a list of the terms (using get_terms) and then querying the posts via WP_Query using the taxonomy option

If we want to display taxonomy name along with post title in backend MYSQL query you can use this query :-

SELECT   p.ID,taxonomy,post_title,post_status,name
FROM    wp_posts p, wp_term_relationships rel, wp_terms t, wp_term_taxonomy te
where  
   p.ID = rel.object_id
  AND t.term_id=te.term_id
  AND t.term_id=rel.term_taxonomy_id
  AND taxonomy in ('taxonomy')
  AND Post_type='post'
  and name='name of taxonomy'
order by post_title

本文标签: List Taxonomy terms along with their posts