How to display post from current Taxonomy in archive page?

You will need to grab the queried object for the page and fill in your taxonomy information dynamically.

if (is_tax() || is_category() || is_tag() ){
    $qobj = get_queried_object();
    // var_dump($qobj); // debugging only
    
    // concatenate the query
    $args = array(
      'posts_per_page' => 1,
      'orderby' => 'rand',
      'tax_query' => array(
        array(
          'taxonomy' => $qobj->taxonomy,
          'field' => 'id',
          'terms' => $qobj->term_id,
    //    using a slug is also possible
    //    'field' => 'slug', 
    //    'terms' => $qobj->name
        )
      )
    );

    $random_query = new WP_Query( $args );
    // var_dump($random_query); // debugging only

    if ($random_query->have_posts()) {
        while ($random_query->have_posts()) {
          $random_query->the_post();
          // Display
        }
    }
} 

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 the tag.php archive templates to process tags and categories separately. You don’t need to use archive.php.

Reference

http://codex.wordpress.org/Class_Reference/WP_Query#Taxonomy_Parameters
http://codex.wordpress.org/Function_Reference/get_queried_object

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)