Action 'save_post' not working for quick edit
-
28-03-2021 - |
Question
I have read other answers to similar questions but none of them solved my problem. This code works great in Editor but on Quick Edit or Bulk Edit it does not appear to fire at all. What am I doing wrong?
// link author display name to Broker Name if Author is Broker
add_action( 'save_post', 'author_is_broker', 200 );
function author_is_broker($post_id) {
// page/post options
global $lwp_options, $Listing;
$post_types = get_post_types();
unset($post_types['listings']);
$post_type = get_post_type();
//Only for listings
if(isset($post_type) && $post_type == "listings"){
// Ignore for autosave
if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) {
return $post_id;
} else {
// If this is a revision, get real post ID
if ( $parent_id = wp_is_post_revision( $post_id ) )
$post_id = $parent_id;
// Get display name of post owner
$broker_id = get_post_field( 'post_author', $post_id );
$broker = get_the_author_meta('display_name', $broker_id);
// Verify directory exists for author
$args = array(
'post_type' => 'wpbdp_listing',
'author' => $broker_id
);
$wp_posts = get_posts($args);
if (count($wp_posts)) {
$is_broker = true;
} else {
return $post_id;
}
// If directory listing has been assigned, user is broker
if (isset($is_broker) && $is_broker == true) {
// add the term
$term = sanitize_text_field($broker);
$Listing->add_listing_category_term('broker', $term);
// update the post
update_post_meta( (int) $post_id, 'broker', $term );
}
else {
return $post_id;
}
}
} else {
return $post_id;
}
}
Solution
It's just a guess, since I haven't tested your code, but... There is a part that looks pretty sketchy for me:
All your actions are run only if this condition is true:
if(isset($post_type) && $post_type == "listings"){
And where that $post_type
variable comes from?
$post_type = get_post_type();
So you don't pass any post_id to that function call... This means that you work with global $post object. But there is no guarantee that such posts exists.
There is a reason why save_post
hook passes post_id as param - you should use it inside your function...
So changing the line above to:
$post_type = get_post_type($post_id);
should solve your problem.
PS. There's no point in doing that:
$post_types = get_post_types();
unset($post_types['listings']);
You don't even use that variable in your code later on...
PPS. save_post
is an action, so you don't have to return anything in it.