Discover in this tutorial how to schedule a function to run in WordPress, in this case to reset permalinks.
Recently I have found myself with a web (inherited) in which, for no apparent reason and every x days, it throws 404 errors when browsing it.
The error is easily fixed by saving the permalinks, but this is only actionable after the 404 error occurs. This still offers an user experience that can be improved.
So, while I’m still investigating the reason, I’ve created a periodic task to reset the permalinks.
WordPress allows you to schedule tasks thanks to the
wp_schedule_event function, which is very handy for executing actions on a periodic basis. In this case the task is to reset the permalinks.
Let’s see how to do it.
Snippet to save permalinks periodically in WordPress
Add the following code snippet to your functionality plugin:
In this code you use the
wp hook in conjunction with the
flush_rules functions to set the periodicity with which the permalinks will be reset.
In this case, the period will be every hour (
hourly), but you can set the period to a different one. For example:
wp_schedule_event(time(), '120min', 'cg_scheduled_event' ); wp_schedule_event(time(), 'daily', 'cg_scheduled_event'); wp_schedule_event(time(), 'weekly', 'cg_scheduled_event');
These lines would allow the task to be executed, respectively:
- Every X minutes (120 in the example)
This is just an example for you to understand how to schedule tasks or actions in WordPress.
In fact, I don’t recommend you to reset permalinks very often as it requires a lot of server resources. Do it only when necessary.
Another option is that instead of resetting the permalinks periodically you do it when a hook is executed (install a theme, a plugin, a CTP…).
Now you know how to run tasks periodically in WordPress and take advantage of it to save the permalinks every X amount of time.
Any questions? Let me know in the comments.
And if you want to give me any suggestion for future tutorials, leave it in the contact form. Advantages of being a subscriber. 😉