Ask your WordPress questions! Pay money and get answers fast! Comodo Trusted Site Seal
Official PayPal Seal

Random Posts using transients WordPress

  • SOLVED

I am using this theme: https://konstantin.blog/themes/semicolon/

You can see the demo here: https://semicolon.kovshenin.com/

I only have 75 posts on the site.

There is a “related posts” section on single posts. It shows the latest four posts from that category.

I want to change it to show: The latest post from that category (in position 1), and then three random posts from that category (in the other three positions).

The tricky bit is: I don't want to use orderby' => 'rand' or ORDER BY RAND() because of speed. I want to use transients.

Follow this solution: http://wordpress.stackexchange.com/a/183296

Give me a related-content.php file I can put in my child theme folder. Please comment your code very well. I want to understand how it works.

<?php
/**
*/
do_action( 'semicolon_related_posts_before' );
$related_posts = Semicolon::get_related_posts();
?>
<?php if ( $related_posts->have_posts() && $related_posts->found_posts >= 2 ) : ?>
<div class="related-content">
<h3 class="related-content-title"><?php _e( 'Try these next...', 'semicolon' ); ?></h3>

<?php while ( $related_posts->have_posts() ) : $related_posts->the_post(); ?>

<article id="post-<?php the_ID(); ?>" class="hentry">
<header class="entry-header">
<a class="post-thumbnail" href="<?php the_permalink(); ?>"><span><?php the_post_thumbnail(); ?></span></a>
<h3 class="entry-title"><a href="<?php the_permalink(); ?>" rel="bookmark"><?php the_title(); ?></a></h3>

<div class="entry-meta">
<?php semicolon_posted_on(); ?>
</div><!-- .entry-meta -->
</header><!-- .entry-header -->

</article><!-- #post-## -->

<?php endwhile; ?>

</div>
<?php wp_reset_postdata(); ?>
<?php endif; // have_posts() ?>
<?php do_action( 'semicolon_related_posts_after' ); ?>

Answers (1)

2017-01-30

Reigel Gallarde answers:

here's the code: http://pastebin.com/2fsReEBN

and here's how it runs..

1.) it gets 1 recent post.
2.) gets 20 posts with random offset. (you can change 20) Save these 20 posts to transient, but only if transient is not present or expired. expiration is set for 2 hours, you can change this.
4.) get 3 random post from transient.
5.) display 1 recent post + 3 random post from transient.


let me know what you think.