I use one of smthemes and there is this code in theme to show related post. it shows the last created related posts, but I want to show related post by random, How can I do that?

global $SMTheme;
if ($SMTheme->get( 'layout', 'related' )) { ?>
                <div class="related-posts">
                <h3><?php echo $SMTheme->_( 'relatedposts' )?>:</h3><ul>
    $categories = get_the_category($postid);

    if ($categories&&($post_cnt<$SMTheme->get( 'layout', 'relatedcnt' ))) {
        $category_ids = array();
        foreach($categories as $individual_category) $category_ids[] = $individual_category->term_id;
        'category__in' => $category_ids,
        'post__not_in' => $showed_posts,
        'showposts'=>$SMTheme->get( 'layout', 'relatedcnt' )-$post_cnt,
        if( count($posts)>0 ) {
            foreach ($posts as $p) {
                $ttl=iconv_substr( $p->post_title, 0, 150, 'utf-8' );
                <li<?php echo (!($first%4))?" class='first'":""?>><?php
                if ($SMTheme->get( 'layout', 'colors' )) {
                } else {
           if(has_post_thumbnail($p->ID))  {
                ?><a href="<?php echo get_permalink($p->ID); ?>" title="<?php printf( $SMTheme->_( 'permalink' ), $p->post_title ); ?>" class='img'><?php
                echo get_the_post_thumbnail($p->ID,array(126,126), array('title'=>$p->post_title, 'alt'=>$p->post_title));
            } else {
                ?><a href="<?php echo get_permalink($p->ID); ?>" title="<?php printf( $SMTheme->_( 'permalink' ), $p->post_title ); ?>" class='img'><img src='<?php echo get_template_directory_uri(); ?>/images/smt/article_related.png' width='126' height='126' alt='article' /></a><?php  
        ?><br /><a href="<?php echo get_permalink($p->ID) ?>" title="<?php printf( $SMTheme->_( 'permalink' ), $p->post_title ); ?>" rel="bookmark" class="related-ttl"><div class='related-bg' style='background:rgb(<?php echo $r.",".$g.",".$b?>)'></div><span><?php echo $p->post_title ?></span></a></li>

    if (!$post_cnt) {
        ?><p><?php echo $SMTheme->_( 'norelatedposts' )?></p><?php
<?php } ?> 

1 Answer 1


In the arguments for get_posts, add 'orderby' => 'rand'. See get_posts in Codex for a full list of available arguments.

$args = array(
    'category__in' => $category_ids,
    'post__not_in' => $showed_posts,
    'showposts' => $SMTheme->get( 'layout', 'relatedcnt' )-$post_cnt,
    'caller_get_posts' => 1,
    'orderby' => 'rand'

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.