Good evening!
I'm trying to adjust the post title + some ACF fields after a user have submitted a custom post type ('booking').
The function I've created almost works! The only problem is that wp_update_post() breaks it...
Adding wp_update_post() to the function will
- Reset the fields stored by ACF
- Remove the chosen category
- Obstruct the redirect to the new post, resulting in "Fatal error: Maximum execution time of 90 seconds exceeded"
What it does though is producing the correct post title! :)
I haven't really managed to understand the logic of action / filter / hooks in Wordpress yet, and therefore would appreciate some help.
Here's the code:
function booking_meta( $post_id, $post, $update ) {
if ( get_post_type( $post_id ) !== 'booking' ) { return; }
// Update ACF fields
$object_id = get_the_ID();
$owner_id = get_the_author_meta( 'ID', $post->post_author );
update_field( 'object', $object_id, $post_id );
update_field( 'owner', $owner_id, $post_id );
// Create post title
$first_name = wp_get_current_user()->user_firstname;
$new_title = get_the_title() . ' to ' . $first_name;
$post_data = array(
'ID' => $post_id,
'post_title' => $new_title,);
wp_update_post( $post_data );
}
add_action( 'wp_insert_post', 'booking_meta', 99, 3 );
I have already tried this without knowing why:
remove_action( 'wp_insert_post', 'booking_meta' );
wp_update_post( $post_data );
add_action( 'wp_insert_post', 'booking_meta' );
That way my first problem is solved but the others persists. It also makes some required datepicker fields in the form turn blank in the resulting post.
wp_update_post
calls thewp_insert_post
action, which means your code gets stuck in an endless loop. You need to useremove_action()
to removebooking_meta
from the hook before you callwp_update_post()