• Hi to all. I am developing a software portal using WordPress. Here is the sample site – https://sample.ifratura.com. My site is almost done. I just need to display a list in sidebar which gets category id from the url (automatically) and displays random posts from the category. I tried myself, but i can’t able to get the category id from the url. Please help me with this.

    Thank you.

Viewing 4 replies - 1 through 4 (of 4 total)
  • Try get_query_vars('cat')

    Moderator keesiemeijer

    (@keesiemeijer)

    example (not tested):

    <?php
    $current_category = get_query_var('cat');
      $random_posts = get_posts('posts_per_page=3&orderby=rand&cat='.$current_category);
      if ($random_posts) {
      $html = '<ul>';
      foreach ( $random_posts as $random_post  ) {
      $html .= '<li><a href="'.get_permalink( $random_post->ID ).'" title="'.esc_attr(strip_tags($random_post->post_title)).'" >'. $random_post->post_title.'</a></li>';
      }
      $html .= '<ul>';
      echo $html;
      }
    ?>

    Thread Starter ashobiz

    (@ashobiz)

    thank you… i tried this…

    <?php
    $current = get_query_var('cat');
    $myposts = get_posts('numberposts=10&orderby=name&cat=4&order=RAND');
    foreach( $myposts as $post ) :	setup_postdata($post);  ?>
    	<li><a href="<?php the_permalink(); ?>"><?php the_title(); ?> v <?php the_field('version'); ?></a></li>
    <?php endforeach; ?>

    but it is not working…

    Thread Starter ashobiz

    (@ashobiz)

    this worked…

    <?php
    $current = get_query_var('cat');
    $args = array( 'numberposts' => 10, 'orderby' => 'rand', 'order' => 'RAND', 'category' => $current );
    $rand_posts = get_posts( $args );
    foreach( $rand_posts as $post ) : ?>
    	<li><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></li>
    <?php endforeach; ?>
Viewing 4 replies - 1 through 4 (of 4 total)
  • The topic ‘Display different post in every category page’ is closed to new replies.