How do I fire a snackbar notice in admin?

I have a custom plugin and want it on occasions to fire the kind of notice that appears and disapears in the left corner like this one:

I found some code in the Gutenberg docs here:

const MySnackbarNotice = () = (
 Snackbar
    Post published successfully.
 /Snackbar
);

But adding this to my admin-enqueued js script obviously doesn't work.

Thanks!

Topic block-editor notices Wordpress javascript

Category Web


Although Andre's answer is partially correct, it's limited to the Javascript function only, and the linked tutorial doesn't provide a complete answer. Here's a complete solution which includes front and back:

add_action('admin_footer-post.php','my_pre_post_update_hook');
add_action('admin_footer-post-new.php','my_pre_post_update_hook');
function my_pre_post_update_hook(){
    global $post;
    ?>
    <script type="text/javascript">
        jQuery(document).ready(function() {
            // We listen to Ajax calls made via fetch
            var temp_fetch = window.fetch;
            window.fetch = function() {
                return new Promise((resolve, reject) => {
                    temp_fetch.apply(this, arguments)
                        .then((response) => {
                            if( response.url.indexOf("/wp-json/wp/v2/posts") > -1 &&
                                response.type === 'basic'
                            ){
                                var clone = response.clone();

                                clone.json().then(function (json) {
                                    if( typeof json.code !== 'undefined' &&
                                        typeof json.code === 'string' &&
                                        typeof json.message !== 'undefined' &&
                                        typeof json.message === 'string'
                                    ){
                                        wp.data.dispatch("core/notices").createNotice(
                                            json.code,
                                            json.message,
                                            {
                                                // type: "snackbar", // Optional
                                                id: 'custom_post_site_save',
                                                isDismissible: true
                                            }
                                        );

                                        // Close default "Post saved" notice
                                        wp.data.dispatch( 'core/notices' ).removeNotice('SAVE_POST_NOTICE_ID');

                                        // You can see all active notices by this command:
                                        // wp.data.select('core/notices').getNotices();
                                    }
                                });
                            }

                            resolve(response);
                        })
                        .catch((error) => {
                            reject(error);
                        })
                });
            };

            // If you want to listen to Ajax calls made via jQuery
            // jQuery(document).bind("ajaxSend", function(event, request, settings){
            // }).bind("ajaxComplete", function(event, request, settings){
            // });
        });
    </script>
    <?php
}

add_action( 'pre_post_update', 'custom_post_site_save', 10, 2);
function custom_post_site_save($post_id, $post_data) {
    if (wp_is_post_revision($post_id)) { // If this is just a revision, don't do anything.
        return;
    } elseif (isset($post_data['post_content']) && strpos($post_data['post_content'], 'myTextString') !== false) {
        $code = 'error';  // Can be one of: success, info, warning, error.
        $response_body = 'My custom message ...';

        $error = new WP_Error($code, $response_body);
        wp_die($error, 200);
    }
}

WordPress has some global actions you can use here. If you want to add your own notice in the lower corner (like the screenshot), you can do that like this:

 wp.data.dispatch("core/notices").createNotice(
        "success", // Can be one of: success, info, warning, error.
        "This is my custom message.", // Text string to display.
        {
          type: "snackbar",
          isDismissible: true, // Whether the user can dismiss the notice.
          // Any actions the user can perform.
          actions: [
            {
              url: '#',
              label: 'View post',
            },
          ],
        }
      );

The important part here is type: "snackbar". You can also leave out the snackbar part and it will appear in the UI above the content:

enter image description here

Here's the full article on WordPress' Block Editor Handbook: https://developer.wordpress.org/block-editor/tutorials/notices/

About

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