Automating is something that you’ll eventually need when developing. If you’re building plugins or custom solutions, you’ll want to automate some operations when a content gets published. WordPress offers scheduling of custom post types out of the box. Let’s see how can we hook on that and automate our code.
You can read about scheduling other CRON jobs in my article on how to use WordPress Cron to Schedule Events.
With my second plugin (the live scores one), I am actually relying on the posts’ date and the WordPress scheduling functionality so I wanted to hook when a post gets published. You could use this functionality for other things such as:
- posting on social media,
- sending newsletter,
- notify customers (for example: on a new product).
So, how can we do that? There are two ways I can think of that could work well:
- hook on the CRON job that WordPress creates,
- hook on the status transition.
Automation on CRON Job
When WordPress schedules a post type, it creates a CRON for the hook
publish_future_post. WordPress uses this hook to publish the post. Here is the core code for it:
We can use the first part of the code that WordPress uses it to check for the timestamp. Let’s see how that’s done:
In this code, we are checking for the timestamp and if it should have been published, we will run our automation code next. We are also checking for the post status and since the core publishing function was already called, we are also accepting the
Automation on Status Transition
This one might be a better or an easier solution to automate your code. We don’t have to check for timestamps or hook on the CRON job. We just need to hook on the post transition hook.
The WordPress core function
wp_transition_post_status is used when the post status has changed.
This function provides us with three different hooks. The first one can be used as a general hook where we need to do more checks for it.
The second hook can be used to specifically define which statuses we want to check.
The third hook can be used for hooking on a specific post status and post type.
Hooking on post status transitions is the easiest way to handle automation on post changes. But you can also hook on various CRON jobs that WordPress (or other plugins) provide for such things.
Have you ever need to run some code when a post status changes? Let us know in the comments below.