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(); ?>
You will need to grab the queried object for the page and fill in your taxonomy information dynamically.
It is not clear if you need this Loop in addition to the main Loop or as a replacement for it. I am assume this is “in addition” as it would effectively remove archive functionality if it were to replace the main query. You;d have no real archives, just a random post from the archive which isn’t very friendly all by itself.
You could use the
category.php
and thetag.php
archive templates to process tags and categories separately. You don’t need to usearchive.php
.Reference
http://codex.wordpress.org/Class_Reference/WP_Query#Taxonomy_Parameters
http://codex.wordpress.org/Function_Reference/get_queried_object
You could consider using the main query with a custom
pre_get_posts
hook:and the usual loop, instead of the additional
WP_Query()
.