I am using the following code to display a random post from the current category in category archive page (using archive.php). However, when in Tag or Taxonomy archive pages, the post is not correctly displayed from the current Tag or Taxonomy (due to the limitation of category only). How can I modify to make it work with Tag and Taxonomy (or just Taxonomy since Category and Tag are also Taxonomies). Thanks!
// assign the variable as current category
$currentcategory = $cat;
// concatenate the query
$args="showposts=1&cat=" . $currentcategory . '&orderby=rand';
$random_query = new WP_Query( $args );
// The Loop
if ( $random_query->have_posts() ) {
while ( $random_query->have_posts() ) {
$random_query->the_post();
// custom template for the random post
}
} else {
// no posts found
}
// Restore original Post Data
wp_reset_postdata();
Edited code in regarding to s_ha_dum’s answer:
<?php // The Query
if (is_tax() || is_category() || is_tag() ){
$qobj = $wp_query->get_queried_object();
// concatenate the query
$args = array(
'posts_per_page' => 1,
'orderby' => 'rand',
'tax_query' => array(
array(
'taxonomy' => $qobj->taxonomy,
'field' => 'id',
'terms' => $qobj->term_id
)
)
);
}
$random_query = new WP_Query( $args );
// The Loop
if ( $random_query->have_posts() ) {
while ( $random_query->have_posts() ) {
$random_query->the_post(); ?>
//HTML tempalte
<?php }
} else {
// no posts found
}
/* Restore original Post Data */
wp_reset_postdata(); ?>