Add meta field after post has been published

I'm trying to add a custom field of event_month when a post is published or saved. I'm using the save_post action and getting the contents of a custom field containing the date and trying to store this in a separate custom field with just the month. This works perfectly when saving a post that has already been created. I've shown my code below.

add_action('save_post', 'update_event_date');

function update_event_date($post_id){

    $post_type = get_post_type($post_id);
    $event_datee = get_post_meta($post_id, '_EventStartDate', true);

    if ($post_type == 'tribe_events'){

        $month = date("m",strtotime($event_datee));
        update_post_meta($post_id, 'event_month', $month);

    }

}

The problem arises when creating a new post. I think this is because the action fires before the _EventStartDate meta has been created and therefore the month can't be taken from this.

The hook is firing correctly and as intended when saving/updating a post but doesn't correctly get the month from the meta when creating a new post.

I'd really appreciate it if someone could provide me with some guidance.

Topic the-events-calendar save-post actions Wordpress

Category Web


You can hook into post_updated action, if you want to access the post's data after it's been published. This hook passes the post's ID, inundated post object, and updated post object.

add_action( 'post_updated', 'update_event_date', 10, 3 );
function update_event_date( $post_id, $post_after, $post_before ){

    $post_type = get_post_type( $post_id );
    $event_datee = get_post_meta( $post_id, '_EventStartDate', true );

    if ( $post_type == 'tribe_events' ) {

        $month = date( "m",strtotime( $event_datee ) );
        update_post_meta( $post_id, 'event_month', $month );

    }

}

Use pre_post_update instead of save_post

Full explanation here

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.