Display notice in block editor after wp_insert_post_data hook

what I cannot understand is how to call the javascript function (file
already enqueued in admin) after the validation from
wp_insert_post_data

You can use the same approach that Gutenberg uses for saving meta boxes (or custom fields), which you can find here on GitHub. It basically uses wp.data.subscribe() to listen to changes in the editor’s state (e.g. whether the editor is saving or autosaving the current post) and after the post is saved (but not autosaved), the meta boxes will be saved.

As for the PHP part, you can just store the error in a cookie and read its value using the window.wpCookies API, which is a custom JavaScript cookie API written by WordPress.

So for example, I used the following when testing:

  • PHP: setcookie( 'event8273_add_notice', 'ERROR: A test error ' . time(), 0, "https://wordpress.stackexchange.com/" );
  • JS: wpCookies.get( 'event8273_add_notice' )

And for checking for and displaying the error, I used this:

( () => {
    const editor = wp.data.select( 'core/editor' );

    // Name of the cookie which contains the error message.
    const cookieName="event8273_add_notice";

    // Set the initial state.
    let wasSavingPost     = editor.isSavingPost();
    let wasAutosavingPost = editor.isAutosavingPost();

    wp.data.subscribe( () => {
        const isSavingPost     = editor.isSavingPost();
        const isAutosavingPost = editor.isAutosavingPost();

        // Display the error on save completion, except for autosaves.
        const shouldDisplayNotice =
            wasSavingPost &&
            ! wasAutosavingPost &&
            ! isSavingPost &&
            // If its status is draft, then maybe there was an error.
            ( 'draft' === editor.getEditedPostAttribute( 'status' ) );

        // Save current state for next inspection.
        wasSavingPost     = isSavingPost;
        wasAutosavingPost = isAutosavingPost;

        if ( shouldDisplayNotice ) {
            const error = wpCookies.get( cookieName );

            // If there was an error, display it as a notice, and then remove
            // the cookie.
            if ( error ) {
                event_save_alert( error );
                wpCookies.remove( cookieName, "https://wordpress.stackexchange.com/" );
            }
        }
    } );
} )();

So just copy that and paste it into your JS file, after your custom event_save_alert() function.

  • Make sure that the script’s dependencies contain wp-data, utils and wp-edit-post.

  • You should also load the script only on the post editing screen for your post type. E.g.

    add_action( 'enqueue_block_editor_assets', function () {
        if ( is_admin() && 'event' === get_current_screen()->id ) {
            wp_enqueue_script(
                'your-handle',
                plugins_url( 'path/to/file.js', __FILE__ ),
                array( 'wp-data', 'utils', 'wp-edit-post' )
            );
        }
    } );