Reputation: 19
I have a piece of code to show a random post type of specific category, it show one post but it does now show random, I wish to show a random post every single time the user refresh this page, any advice and suggestions will be greatly ppreciated.
Thansk :)
<?php
global $post;
$args = array(
'post_type'=>'topics',
'showposts'=>'1',
'cat'=> 8,
'orderby' => 'rand'
);
$query = 'orderby=rand';
$my_query = new WP_Query($args);?>
<?php
while ($my_query->have_posts()) : $my_query->the_post();?>
<a href="<?php the_permalink(); ?>"><?php the_title(); ?></a>
<?php endwhile;
wp_reset_query(); ?>
Upvotes: 0
Views: 2026
Reputation: 131
Hi Use this code for getting random posts..It works for me !!!
<h1>Random Posts</h1>
<ul>
<?php
$args = array( 'posts_per_page' => 5, 'orderby' => 'rand','category' =>'8','post_type' => 'topics' );
$rand_posts = get_posts( $args );
foreach ( $rand_posts as $post ) :
setup_postdata( $post ); ?>
<li><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></li>
<?php endforeach;
wp_reset_postdata(); ?>
</ul>
Here it displays a list of 5 posts selected randomly by using the MySQL RAND() function for the orderby parameter value
Upvotes: 3