Engineering
WordPress: How to trigger the Post publish event
How to hook into and trigger the WordPress post-publish event for custom automation.
1 min read
These days I’m working on a news publishing app, focused on its back-end API. Now that we’re in the final stage of development, we’ve started adding push notifications, so I needed a way to trigger an event the moment a WordPress post is published, in order to send push notifications to Android and iOS devices. While experimenting with WordPress functions, I came up with this solution, which is handy, and I believe it’ll be useful for anyone wanting to build a similar feature.
By the way, if you know a better way to handle this, please let me know. Improvements are always welcome for apps dealing with millions of users, right?
/*
* Add this function somewhere in functions.php
* You will see there is nothing is magic in WordPress
**/
function on_all_status_transitions( $new_status, $old_status, $post ) {
if ('publish' == $new_status && 'publish' != $old_status && 'trash' != $old_status) {
// Your code comes here
}
}
add_action( 'transition_post_status', 'on_all_status_transitions', 10, 3 );
The gist is still at https://gist.github.com/yoosuf/3890f3789754afe65525 .
Related reading
-
Trigger and Shoot – Slim WordPress plugin
Trigger and Shoot: a slim, lightweight WordPress plugin for triggering actions on post events.
-
A Better Way to Show WordPress Database Errors
A cleaner approach to displaying WordPress database errors for easier debugging during development.
-
How to Enjoy Programming in the LLM Era
Why coding feels less fun since AI assistants arrived, what METR's productivity trial and Stack Overflow's trust data actually show, and the personal habits and team practices that keep comprehension of your own system yours.