Run a Function When Post Published

in WordPress Tutorials

When developing WordPress plugins, it is very common for developers to tie into some of WordPress’s core actions, allowing for a plugin’s custom functions to be run when the core action takes place.

I’m going to show you how to tie a custom function into the action that takes place when a post is published, which will allow us to execute our custom function every time the “publish” button is clicked.

Doing this can be extremely useful for a huge number of possible reasons:

  • If you want to schedule something to happen when a post is published
  • If you want to send out an email to your subscribers when posts are published
  • If you want to limit post title lengths
  • If you want to do anything related to the publication of a post

For the purpose of this post, I’m not going to write a function that does anything, but I am going to show you how to tie any function you want into the publish post action.

First, write your function that will perform some task or other:

// function to be executed when a post is published
function run_when_post_published()
    // your function code here

Next is to tie the function into the publish_post action:

add_action('publish_post', 'run_when_post_published');

Your function run_when_post_published will now be executed every time a post is published.

There’s a problem with the publish_post action though: it also runs whenever a post is updated. So, depending on what your function does, this may not be optimal. Luckily, WordPress also has actions that allow us to run our function only when a post is newly published:

add_action('new_to_publish', 'run_when_post_published');
add_action('draft_to_publish', 'run_when_post_published');
add_action('pending_to_publish', 'run_when_post_published');

Now, your function will only run when:

  1. Your post is published (updated) for the first time
  2. Your post transitions from draft to published
  3. Your post transitions from pending to published

Note: the actions described above will not work for Custom Post Types. However there are similar action hooks for Custom Post Types I have detailed on my website.



Comments (2)

  • Comment by webdhm

    I tried that but nothing happens. when I’m using publish_post it works fine, but there is the issue when updating a post

  • Comment by Pippin

    Try using “save_post”