How do I create a random post but it shouldnt be change when the page is refreshed
I want a random post that will last for a day and after 24 hours or a day,
it will change randomly the post ,
will be that possible? or are there a plugin that exactly does that ,
actually what Im trying to create is like a “Random Tip For the Day”, you know something like that
I hope someone understand my question
please help,any help will be appreciated.
Here is some code doing what you’ve asked and using the ideas others have highlighted:
get_posts() help Plus the way I have coded it should make the Tip of the Day post change at midnight every day.
This can be improved upon because we are showing random there is nothing stopping the same post showing twice in a row…
A transient seems like a lot of extra effort. Instead, just use the fact that MySQL’s RAND function can be seeded for reproducible random numbers.
Use a function like this:
Then, around your WP_Query or get_posts or whatever it is that you have retrieving this single post, use this filter code:
This adds the filter, gets the post, then removes the filter.
By setting the seed to a number that changes once a day, then the random will produce the same answer every time for that day. Then it will give a different random number every DAY_IN_SECONDS goes by.
No transients, no need for storage of data.
Update for WordPress 4.5+
Ordering by random, containing a seed value, is now supported in WordPress 4.5+:
See ticket #35692 for more information.
You can use the Transients API, as kaiser said. Just store a random post ID with a lifetime of 24h. To select a random post you can set the
orderby
argument ofget_posts()
to"rand"
.Use case example:
Interact with the Transients API. You could attach something like “sticky” to it or a specific category or term.