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.
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.
Share Improve this question asked Oct 20, 2019 at 16:32 user5710user5710 3151 gold badge4 silver badges6 bronze badges2 Answers
Reset to default 0I 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/tutorials/wordpress/real-cron-job/, then with the help of wp_schedule_event
you can create a weekly task to update your posts.
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!
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745064673a4609183.html
评论列表(0条)