I'm currently doing some work with the WP Job Board Manager plugin and I'm wanting to create a function that will fire when a new job is published.
The first thing I did was to create the general hook to find out what the post type was:
function newJobAdded() {
$posttype = get_post_type( $post );
mail('email@email.com','new job published',$posttype);
}
add_action( 'publish_post', 'newJobAdded' );
Which sent me an email telling me that the post type was: job_listing. I then created a new function that would only fire if the custom post type was job_listing
function newJobAdded() {
$posttype = "job_listing";
if ($post->post_type == $posttype) {
mail('email@email.com','new job published','done new job publish');
}
}
add_action( 'publish_post', 'newJobAdded' );
However, nothing happens when I do this. Am I missing something simplistic and noobish?
Try with
function newJobAdded($ID, $post) {
}
instead of
function newJobAdded() {
}
Reference: publish_post
The 'publish_post' action is post type specific. So if you have a custom post type, you need to change the hook you use. if your post type is job_listing
, the hook you should use is publish_job_listing
.
function newJobAdded($ID, $post ) {
mail('email@email.com','new job published','done new job publish');
}
add_action( 'publish_job_listing', 'newJobAdded', 10, 2 );
A more general hook will be transition_post_status
which fires everytime a post's status is changed. You can use $old_status
and $new_status
to check the previous and new status of a post then do something.
For a new post, you can something like this: (Requires PHP 5.3+)
add_action( 'transition_post_status', function ( $new_status, $old_status, $post )
{
if( 'publish' == $new_status && 'publish' != $old_status && $post->post_type == 'my_post_type' ) {
//DO SOMETHING IF NEW POST IN POST TYPE IS PUBLISHED
}
}, 10, 3 );
EDIT
For older versions, use
add_action( 'transition_post_status', 'so27613167_new_post_status', 10, 3 );
function so27613167_new_post_status( $new_status, $old_status, $post )
{
if( 'publish' == $new_status && 'publish' != $old_status && $post->post_type == 'my_post_type' ) {
//DO SOMETHING IF NEW POST IN POST TYPE IS PUBLISHED
}
}
The 'publish_post' action is post type specific. So if you have a custom post type, you need to change the hook you use. IE, if your post type is 'job_listing', the hook you should use is 'publish_job_listing'.