WordPress.org

Support

Support » How-To and Troubleshooting » [Resolved] Change order to Random for related posts list

[Resolved] Change order to Random for related posts list

  • I have created a bit of code that is hooked beneath each post. It displays the thumbnail and title of 4 posts from the same category as the preceding post.

    It works perfectly, the only thing I want to change is to have it choose the 4 posts from the category RANDOMLY. Currently it seems to be pulling th 4 most recent posts.

    How do I change my code to facilitate this?

    function my_related_posts() {
    if (is_single()) {
    	global $post;
    	$current_post = $post->ID;
    	$categories = get_the_category();
    foreach ($categories as $category) :
    	?>
    <div class="featured-posts-box"><div class="my-recent-posts"><h4>You may also like...</h4><ul class="top-featured-image">
    	<?php
    	$posts = get_posts('numberposts=4&category='. $category->term_id . '&exclude=' . $current_post);
    foreach($posts as $post) :
    	?>
    <li  class="top-featured-image"><span><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></span> <?php if ( has_post_thumbnail()) : the_post_thumbnail('thumbnail'); endif; ?></li>
    	<?php endforeach; ?><?php endforeach; ?>
    </ul>
    </div>
    </div>
    	<?php
    		}
    	wp_reset_query();
    }
Viewing 4 replies - 1 through 4 (of 4 total)
  • esmi

    @esmi

    Forum Moderator

    Try adding orderby=random to your get_posts arguments.

    http://codex.wordpress.org/Function_Reference/WP_Query

    I tried that but I must have made a mistake with the syntax. Where exactly should I put it? Can you give an example? I’m not great at my php.

    esmi

    @esmi

    Forum Moderator

    $posts = get_posts('numberposts=4&orderby=random&category='. $category->term_id . '&exclude=' . $current_post);

    Yes that worked thank you. I just changed &orderby=random to &orderby=rand

    function my_related_posts() {
    if (is_single()) {
    	global $post;
    	$current_post = $post->ID;
    	$categories = get_the_category();
    foreach ($categories as $category) :
    	?>
    <div class="featured-posts-box"><div class="my-recent-posts"><h4>You may also like...</h4><ul class="top-featured-image">
    	<?php
    	$posts = get_posts('numberposts=4&orderby=rand&category='. $category->term_id . '&exclude=' . $current_post);
    foreach($posts as $post) :
    	?>
    <li  class="top-featured-image"><span><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></span> <?php if ( has_post_thumbnail()) : the_post_thumbnail('thumbnail'); endif; ?></li>
    	<?php endforeach; ?><?php endforeach; ?>
    </ul>
    </div>
    </div>
    	<?php
    		}
    	wp_reset_query();
    }
Viewing 4 replies - 1 through 4 (of 4 total)
  • The topic ‘[Resolved] Change order to Random for related posts list’ is closed to new replies.
Skip to toolbar