我使用下面的代码在category archive页面(使用archive.php)中显示当前类别中的随机帖子。但是,在标记或分类归档页面中,无法从当前标记或分类中正确显示帖子(由于仅限于类别的限制)。如何修改以使其与标记和分类法(或者仅仅是分类法,因为类别和标记也是分类法)一起工作。谢谢
// 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();
编辑了有关s\\u ha\\u dum答案的代码:<?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(); ?>