WordPress.org

Ready to get started?Download WordPress

Forums

[resolved] Change order to Random for related posts list (5 posts)

  1. cyndimarie
    Member
    Posted 1 year ago #

    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();
    }
  2. esmi
    Theme Diva & Forum Moderator
    Posted 1 year ago #

    Try adding orderby=random to your get_posts arguments.

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

  3. cyndimarie
    Member
    Posted 1 year ago #

    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.

  4. esmi
    Theme Diva & Forum Moderator
    Posted 1 year ago #

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

  5. cyndimarie
    Member
    Posted 1 year ago #

    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();
    }

Topic Closed

This topic has been closed to new replies.

About this Topic

Tags

No tags yet.