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

Automatically Query Parent Taxonomy WordPress

  • SOLVED

I have a custom taxonomy on my site that I query from the sidebar of the currently displayed term. Say I am on the `Term X` archives, then my custom post type of Products with the term of `Term X` are shown.

I would like to avoid an empty result so I would like to query up the chain until posts are found. For example:

Term W (5 products)
-- Term X (1 product)
--- Term Y (0 products)
---- Term Z (0 products)


If I were to query `Term Z` then I would like to show the result from `Term X` and stop there.

This is the code I came up with, but I know it's incorrect and doesn't accomplish the above.


<?php $queryvar = query_posts(array('post_type' => 'event',$the_taxonomy => $the_term,'showposts' => 10 ) ); ?>
<?php if(count($queryvar) < 1) {

do
{
$parents = get_ancestors( $term, $the_taxonomy );
$the_term = $parents[0];
$queryvar = query_posts(array('post_type' => 'event',$the_taxonomy => $the_term,'showposts' => 10 ) );
$term = get_term($the_term, $the_taxonomy);
echo $term->name;
}
while (count ($queryvar) == 0);
}
else { $the_term = get_term_by( 'slug', get_query_var( 'term' ), get_query_var( 'taxonomy' ) );
}?>

Answers (2)

2013-10-11

Remy answers:

Can you show the code you're using ?


neoian comments:

I have added it to the OP.


Remy comments:

Here is a code snippet I tried in an archive.php page on my local WP install


<?php
// get term object
$term = get_queried_object();

// if term has no post, use the custom function, else uses the normal loop for the archive page
if ( $term->count == 0 ) {
rp_loop_term( $term );
} else {
// normal loop to display the posts here
}
// custom recursive function to get the first tax with posts
function rp_loop_term( $term_object ) {
if ( $term_object->count > 0 ) {
$new_query = new WP_Query( array(
'post_type' => 'event',
'tax_query' => array(
'taxonomy' => $term_object->taxonomy
'field' => 'id',
'terms' => $term_object->term_id
),
'showposts' => 10
)
);
while( $new_query->have_posts() ) {
$new_query->the_post();
// display the posts with template_tags
}
} else {
// we get the parent object of the current term, then re-use the function
$term_object = get_term( $term_object->parent, 'category' );
rp_loop_term( $term_object );
}
}
?>

2013-10-12

Galia Bahat answers:

get_ancestors gets you the ids of all the ancestors in order - Y, then X, then W. Loop through the output of get_ancestors, for each one get the term, and then test whether it's empty.