I want to do something when a post is published (doesn’t matter if updated [draft -> publish] or just created)

In my plugin I tried different actions to try this. I tried the following code to detect when which event is triggered:

function new_post() { file_put_contents('debug.log', 'new_post', FILE_APPEND); }
function publish_post() { file_put_contents('debug.log', 'publish_post', FILE_APPEND); }
function pending_post() { file_put_contents('debug.log', 'pending_post', FILE_APPEND); }
function draft_post() { file_put_contents('debug.log', 'draft_post', FILE_APPEND); }
function auto_draft_post() { file_put_contents('debug.log', 'auto_draft_post', FILE_APPEND); }
function future_post() { file_put_contents('debug.log', 'future_post', FILE_APPEND); }
function private_post() { file_put_contents('debug.log', 'private_post', FILE_APPEND); }
function inherit_post() { file_put_contents('debug.log', 'inherit_post', FILE_APPEND); }
function trash_post() { file_put_contents('debug.log', 'trash_post', FILE_APPEND); }
function save_post() { file_put_contents('debug.log', 'save_post', FILE_APPEND); }

add_action('new_post', 'new_post', 10, 2);
add_action('publish_post', 'publish_post', 10, 2);
add_action('pending_post', 'pending_post', 10, 2);
add_action('draft_post', 'draft_post', 10, 2);
add_action('auto-draft_post', 'auto_draft_post', 10, 2);
add_action('future_post', 'future_post', 10, 2);
add_action('private_post', 'private_post', 10, 2);
add_action('inherit_post', 'inherit_post', 10, 2);
add_action('trash_post', 'trash_post', 10, 2);
add_action('save_post', 'save_post', 10, 2);

But it seems like this is only working if I plan a post to be published in the future. In this case only ‘publish_post’ and ‘save_post’ is triggered.

Do I need to configure something or why are the other ones not working?

1 Answer
1

If your aim is to trigger code when a post is published, as in, the post_status of the post is set to publish, then you can hook into save_post like this:

function cc_publish_wpse_263985( $postid ) {

    // check if post status is 'publish'
    if ( get_post_status( $postid ) == 'publish')  ) {

        // do something here

    }

}
add_action( 'save_post', 'cc_publish_wpse_263985' );

Leave a Reply

Your email address will not be published. Required fields are marked *