List posts by taxonomy tag
-
I want to list posts that are tagged in a custom taxonomy under headings that are tags in that taxonomy:
Tag1
* Post x
* Post yTag2
* Post zTag3
…I also want a list/index of the tags at the top of the page that are linked to each section, for quick access:
Tag1 | Tag2 | Tag3… etc
I’ve put together some code that works, but I see it makes a lot of database queries. I’m not a leet PHP programmer, and I can’t help feeling I’m not doing this the best way. Does anyone have any ideas to optimise it?
(In the meantime, this code does work, so it is usable if anyone else wants to achieve the same thing. You can see it in action at https://nfcw.net/?p=2921 )
<?php // output quick links list of countries $terms = get_terms('countries'); if (count($terms)) { echo "<h3>Quick links</h3>"; echo "<p style=\"text-align:center;\">"; } $i=0; // counter for printing separator bars foreach ($terms as $term) { $wpq = array ('taxonomy'=>'countries','term'=>$term->slug); $query = new WP_Query ($wpq); $article_count = $query->post_count; echo "<a href=\"#".$term->slug."\">".$term->name."</a>"; // output separator bar if not last item in list if ( $i < count($terms)-1 ) { echo " | " ; } $i++; } if (count($terms)) { echo "</p>"; } foreach ($terms as $term) { $wpq = array ('taxonomy'=>'countries','term'=>$term->slug); $query = new WP_Query ($wpq); $article_count = $query->post_count; echo "<h3 class=\"term-heading\" id=\"".$term->slug."\">"; echo $term->name; echo "</h3>"; if ($article_count) { echo "<ul>"; $posts = $query->posts; foreach ($posts as $post) { echo "<li><a href=\"".get_permalink()."\">".$post->post_title."</a> <span class=\"tiny\">".get_the_time('j M y')."</span></li>"; } echo "</ul>"; } echo "<p><a href=\"#top\">Back to top</a></p>"; } ?>
Cheers,
M ??
Viewing 7 replies - 1 through 7 (of 7 total)
Viewing 7 replies - 1 through 7 (of 7 total)
- The topic ‘List posts by taxonomy tag’ is closed to new replies.