2

I'm writing a plugin that fetches some data from an XML file and then creates a post based on its content.

I was thinking of using wp_insert_post() to publish the new post, but I have some functions that are hooked to publish_post.

After digging in the \wp-includes\post.php, I couldn't find any publish_post action hooks that are triggered by this event.

There were only these hooks related to my case:

// Fires once an existing post has been updated.
do_action( 'post_updated', $post_ID, $post_after, $post_before);
// Fires once a post has been saved.
do_action( 'save_post', $post_ID, $post, $update );
//Fires once a post has been saved.
do_action( 'wp_insert_post', $post_ID, $post, $update );

Am I missing something? Or doesn't wp_insert_post() trigger the publish_post action?

1 Answer 1

3

It's triggered in wp_publish_post() that calls:

wp_transition_post_status( 'publish', $old_status, $post );

that fires up action calls, dynamically with:

do_action( "{$new_status}_{$post->post_type}", $post->ID, $post );

where "{$new_status}_{$post->post_type}" becomes "publish_post" in your case.

5
  • Thanks! So, I should insert the post as a draft, and then publish it using wp_publish_post() right after it?
    – Johansson
    Commented Aug 3, 2017 at 9:42
  • If you have event calls that depend on the transition from e.g. draft to publish, then I think I would use that approach, instead of adding my own do_action calls, even though it adds an extra update call. I'm assuming you're not importing tons of data ;-) Or maybe you can just change your plugins to hook into wp_insert_post calls?
    – birgire
    Commented Aug 3, 2017 at 9:55
  • Actually I was importing tons of data :D The plugin is not created by me unfortunately, and it has a lot of action hooks, leaving me unable to go for that approach. I seem silly today, since I want to ask you what did you mean by adding your own do_action call? :)
    – Johansson
    Commented Aug 3, 2017 at 10:09
  • 1
    We can make do_action calls to trigger core events, but we have to be careful doing it manually, not to create infinite loops or escalading it to other strange errors, if we call it in wrong places. It might not be future proofed too! Sometimes wp-cli is useful to e.g. avoid PHP timeouts. Even possible to write custom commands. Otherwise I recall posting to "Faster way to wp_insert_post & add_post_meta in bulk" that might help?
    – birgire
    Commented Aug 3, 2017 at 10:18
  • 1
    Thanks. Yes that would certainly do it. I think I'll go with the simple solution. I can wait an hour for the import to finish, I'm not in a hurry :)
    – Johansson
    Commented Aug 3, 2017 at 10:20

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.