0

If I run a query with some args and get a list of posts, how can I organize the posts separated by category and display the title of each category?

$array_out = array();

$args = array( 
'orderby' => 'title',
'order' => 'ASC', 
);

$the_query = new WP_Query( $args );
while ( $the_query->have_posts()) : $the_query->the_post(); 

$terms = get_the_terms( $post->ID, 'category'); 
foreach($terms as $term){
    $term_link = get_term_link($term, 'category');
    $array_out[] = '</br><a href="'.$term_link.'">'.$term->name.'</a> </br>';
}
endwhile; 

$array_clean = array_unique($array_out);

foreach($array_clean as $array_single){

echo $array_single;

}

This gets me a list of unique category terms for all my posts with no duplicates. Im stuck from here though as I would like to list all the posts of the query grouped by the terms I got. The point is I do not want to get all the category terms first then query posts for each term, like I have seen suggested elsewhere. I need to do it after I get a list of posts from a query. So I thought

  1. Query for posts with some args
  2. while loop through posts to find list of terms of categories
  3. Array_unique found terms because there will be duplicates
  4. Then query for posts again for each category term found in step 2

Would this work? Im not exactly sure what Im doing as Im new. I just want to be able to: No matter what posts I'm querying for with arguments of my choice to put out a list of posts grouped by category terms separated by term name. Is it hard to understand what I'm asking for? I dont know how else to put it.

  • What do you mean by organize? Group the posts together by category? Sort by category? Nest posts hierarchically? – Jared Cobb Jul 18 '14 at 16:08
  • Group posts by category, with the title of category above each group of posts. – dustin Jul 18 '14 at 16:22
  • possible duplicate of How can I list posts in an archive but grouped by categories – Brad Dalton Jul 18 '14 at 16:52
  • In my while have posts loop of the query I did a get_the_terms and put them into an array. After the endwhile I did a array_unique of the terms. This got me a list of the category terms (with no duplicates) of all the posts I queried for. Im not sure where to go from here. – dustin Jul 18 '14 at 17:22

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.