Call a PHP function after a post published in WordPress
Today in this article, I am going to tell you how to call a PHP function when a post updates with status “publish” or a new post publishes on a WordPress site. In a nutshell, we just have to run PHP code after a post published on a WordPress site. The code will be in a specific function.
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 using the publish_post action hook:
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 piece of code that I have used the action hook and passed 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 the status of a post become “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 the official WordPress developer page where you can also find an amazing example of sending an email when a post updates and the status is “publish” or after a new post publish.
Awesome work! This helped a lot. Thank you…