Call a PHP function after a post publish in WordPress

By Faruque Ahamed Mollick

Today in this article, I am going to tell you how to call a PHP function when a post update with status “publish” or a new post publishes on a WordPress site.



WordPress has an action which is publish_post that will trigger at the time of a post updated and the status of the post be “publish”.

Below is the code structure:

function call_after_post_publish() {
     // Code to be run after publishing the post
}
add_action( 'publish_post', 'call_after_post_publish', 10, 2 );

You can see in the above code that I have used the action hook and pass the function in it. All the required code will be inside the custom function call_after_post_publish() that I have created.

Well, we can also get the id of the author, author name, author email, post title, the link of the post inside the function just as you can see below:

function call_after_post_publish() {
     $author = $post->post_author; /* Post author ID. */
     $name = get_the_author_meta( 'display_name', $author );
     $email = get_the_author_meta( 'user_email', $author );
     $title = $post->post_title;
     $permalink = get_permalink( $ID );
     $edit = get_edit_post_link( $ID, '' );
}

Well, you can do this for any type of WordPress custom post. For example, if you want it for a custom post type “shop”, then use the given code below:

add_action( 'publish_shop', 'call_after_post_publish', 10, 2 );

After that whenever, shop type post status be “publish” then it will run the code inside your custom function call_after_post_publish(). The syntax of the action is {status}_{post_type}.

Add a custom widget area for custom WordPress theme – Theme development

The Right Way Of Adding Custom CSS On WordPress

With this, you just can run the custom code that you need to run for your requirement. Not only for normal default post type but also you can do it for any type of custom post type just by using syntax like you can see below:

{status}_{post_type}

That is amazing. Isn’t it?

To know more about it visit official WordPress Codex page where you can see an example of sending an email when a post update and the status is “publish” or after a new post publish.

Leave a Reply

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