Ask your WordPress questions! Pay money and get answers fast! Comodo Trusted Site Seal
Official PayPal Seal

Custom Taxonomy Listing Help WordPress


I have setup two custom taxonomies for a custom post type that I have created. The post type is called beer, and the two taxonomies are country and brewers.

I would like to list them like this.


I can pull the countries using this code.

$terms_country = get_terms('country');
foreach ($terms_country as $term_country) {
echo "<h3 class=\"country-heading\" id=\"".$term_country->slug."\">";
echo '<a href="/beers/country/' . $term_country->name . '">' . $term_country->name . '</a>';
echo "</h3>";

I need to query the country term to list the Brewers that have that taxonomy attached to the post as well. I would then like to list the post itself.

Answers (1)


Dbranes answers:

Hi, here is one idea to use only a single db query:

$sql=" SELECT
{$wpdb->term_relationships}.object_id as post_id,
{$wpdb->posts}.post_title as beer_name,
{$wpdb->terms}.name as term_name,
{$wpdb->term_taxonomy}.term_id as term_id,
{$wpdb->terms}.slug as term_slug
FROM {$wpdb->terms}
LEFT JOIN {$wpdb->term_taxonomy}
ON {$wpdb->term_taxonomy}.term_id = {$wpdb->terms}.term_id
LEFT JOIN {$wpdb->term_relationships}
ON {$wpdb->term_taxonomy}.term_taxonomy_id = {$wpdb->term_relationships}.term_taxonomy_id
LEFT JOIN tfl_posts
ON {$wpdb->term_relationships}.object_id = {$wpdb->posts}.id
WHERE {$wpdb->term_taxonomy}.taxonomy in ( 'country','brewers')
AND {$wpdb->posts}.post_status ='publish'";

$data =$wpdb->get_results($sql,ARRAY_A);


foreach($data as $d){

echo "<pre>";


echo "<ul>";

foreach($beers_per_country as $country=>$beers){
echo "<li>".$country."<ul>";
foreach($beers as $beer){
foreach($brewers_per_beer[$beer['post_id']] as $brewer){
foreach($beers_per_brewer[$brewer['brewer_name']] as $item){
foreach($a as $brewer_name){
echo "<li>".$brewer_name."<ul>";
foreach($c as $item){
echo "<li>".$item."</li>";
echo "</ul></li>";
echo "</ul></li>";
echo "</ul>";
echo "</pre>";

Drew Clardy comments:

I have added this in, and it is just giving a list of the countries with no brewers.

Drew Clardy comments:

Adding an image to show the results of the page.