0

What I'm trying to achieve: my homepage displays 3 random posts from each of 5 different categories. That part is easy.

What's a little unique and I can't quite figure out how to accomplish, I would like those posts to change automatically every week.

That way if the user comes back a couple times during the week, they see the same posts, but on a weekly basis the query should update to make it essentially look like a bunch of new content has been added (or at least previously written content is now featured).

How would I go about doing that? Thanks.

2 Answers 2

0

I see two approaches: via cron job... or website / page cache which lasts 1 week.

In case you want to do the cache option: you just need to add 'orderby' => 'rand' to your WP_Query and install a caching plugin for your page, then set it up for 1 week.

CronJob: you need to setup a script which starts every week. For this you need to setup the cron job for your WordPress - https://www.siteground.com/tutorials/wordpress/real-cron-job/, then with the help of wp_schedule_event you can create a weekly task to update your posts.

0

A nice middle way between caching and cronjob is to use transients

You can write a little function that handles the setting and getting of transients.

$posts = get_transient( 'recent_posts' );
if ( false == $posts ) :
$posts = new WP_Query( array (
  'orderby' => 'rand',
  'fields' => 'ids'
));
set_transient( 'recent_posts', $posts, 60*60*12 );
endif;
return $posts;

In the transient you store the ids of the posts that you've called before in a WP_Query. You then set the expiry of the transient for a week and your function just checks if there is a transient already. If not, create a transient with your random posts ids.

The code isn't tested, it's merely an example of how it can be used. Let me know how it goes!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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