1

I would like to know if there is a hook that fires when a new CPT is published and its postmeta has been inserted.

I was using publish_mycpt but found that the postmeta wasn't being saved at that point. I would like my hook to run only for this custom post type, not for all posts.

The function I will be calling via the action hook is also used by a scheduled cron job, so it's not only called when a new post is published via the administration interface, not sure if this is important or not.

1 Answer 1

1

I believe you can do it using the save_post hook, than do a conditional check for the post's post-type and the value of its post meta.

add_action( 'save_post', 'do_some_function');
function do_some_function($post_id) {
    global $post;
    $post_type_as_taxonomy = array('cpt-1','cpt-2'); // this is your hooked custom post types
    $post = get_post( $post_id );
    if(in_array($post->post_type, $post_type_as_taxonomy) && $post->post_status=='publish'){ // check if the post is hooked & published
        $my_meta = get_post_meta($post_id, 'my-meta', true); // check if  it has a post meta with the ket 'my-meta'
        if($my_meta){
            // do your hook function here
        }
    }
}
3
  • Works with a small modification, 'wp_insert_post' instead of 'save_post'. Not sure why that is so, I thought the two hooks were the same.
    – urok93
    Commented Sep 5, 2012 at 8:08
  • Another question to help me understand what's happening here, since the action passes both the post id and the post itself do_action('wp_insert_post', $post_id, $post); would I also be able to call the function like so: function do_some_function($post) instead of using the $post_id parameter?
    – urok93
    Commented Sep 5, 2012 at 8:19
  • That is interesting. Never though it would work using 'wp_insert_post'. You can 'print_f($post) inside the 'do_some_function' than do a 'wp_die()' to find out what is inside the $post.
    – ifdion
    Commented Sep 5, 2012 at 22:17

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.