Wordpress custom post action hook

2019-08-11 03:52发布

问题:

I'm working on a plugin for wordpress that I would like to fire every time a custom post of the type 'job' is posted, published, edited, trashed, untrashed, etc. (basically whenever there is an update to that post type).

I'm having a bit of trouble finding the correct action hook to call. I have searched, and from my understanding I can't use for example (publish_post) because I am using a custom post type, so it should be something along the lines of (publish_job). However, that doesn't seem to work for me either, if I go in to the jobs category and publish a draft in the jobs category.

So, I guess I have two questions:

1) What is the correct action I should be using in the context of a custom post type.

2) a. Is there some sort of action that I can use to encompass all sorts of changes to the jobs category (ie: post editing, publishing, unpublishing, trash/untrash, etc). b. If not, how would I go about calling add_action for all of those possible actions.

Thank you!

回答1:

Not sure if there is just one action but here are the various actions:

  • save_post (create or update)

  • wp_delete_post (deleted)

  • wp_trash_post (trashed)

so you can do something like this:

function my_callback_function() {

    if($post->post_type = 'job') {
        //do something here
    }
}

all_actions = array('save_post','wp_delete_post','wp_trash_post');

foreach ($all_actions as $current_action) {

    add_action($current_action, 'my_callback_function');
}


回答2:

Do you mean something like this? This should fire every time a custom post 'job' status has changed. If you want to do action specific stuff just add a check into the if clause.

<?php    
function run_on_all_job_status_transitions( $new_status, $old_status, $post ) {
    if ($post->post_type == 'job') {
            // do stuff
    }
}
add_action( 'transition_post_status', 'run_on_all_job_status_transitions', 10, 3 );