Possible conflict with CMB2 and wp_update_post
-
Hello!
I think I might have stumbled with a bug, but it might just be that I’m using the wrong hook for what I’m attempting to do:
I have a hierarchical CPT called “Events”, with a couple of cmb2 metaboxes. What I want is for child events to update the publish date of their parent, so that the parent moves up in my loops (ordered by date in descending order) everytime a new child event is added.
To achieve that, I’ve hooked onto “wp_insert_post” to run a function which checks if the event is a child. Then, gets the event’s parent, checks if the child’s date has passed (i.e. the child is published, not programmed for publishing), then checks if the child’s date is more recent than the parent’s and, finally, runs wp_update_post for the parent to clone the child’s post date:
function update_event_parent_date($event_ID, $event){ if($event->post_type === 'eventos' && $event->post_parent !== 0 && $event->post_status == 'publish'){ //If it is a child event $parent_event = get_post($event->post_parent); //Get the parent if( $parent_event !== null && $parent_event->post_parent === 0 ){ //If the parent exists and is not the child of another post $time_now = current_datetime(); $post_time = get_post_datetime($event_ID); $parent_p_time = get_post_datetime($parent_event->ID); if( ($time_now > $post_time) && ($post_time > $parent_p_time) ){ //Check dates //If it checks out, give the parent event the same date as the child $new_date = $event->post_date; $new_date_gmt = $event->post_date_gmt; wp_update_post( array ( 'ID' => $parent_event->ID, 'post_date' => $new_date, 'post_date_gmt' => $new_date_gmt ), false, false ); } } } } add_action('wp_insert_post', 'update_event_parent_date', 10, 2);
The problem:
This seems to be working fine. It updates the date when expected. However, once it does, it overwrites all of the parent event’s cmb2 meta fields with those of the child whose date was copied. It is worth noting that only the cmb2 metas are overwritten, since I’m also using Yoast SEO and those metas keep working as expected.
I’m unsure if this could be a bug or just that I should be using another hook for this functionality, any advice or suggestion is welcome. Thanks!
- The topic ‘Possible conflict with CMB2 and wp_update_post’ is closed to new replies.