Remove Admin Notice on page refresh

I have a simple question about admin notices. I want to display a message like ‘Record updated successfully’, and when user refresh again same page, then this notice should not be there as no record is updated again.

Just like settings Api, there is notice as ‘Settings saved.’ and when we refresh the page the notice is not there. I see in URI argument is there as

http://example.com/wp-admin/admin.php?page=xyz&settings-updated=true

I know here settings-updated=true is the key, and it disappear immediately and user can hardly notice it. But I don’t know how it disappears after taking effect. I think I am missing very simple and basic trick.

Any help highly appreciated

1 Answer
1

This is done by wp_admin_canonical_url:

  • It calls wp_removable_query_args to fetch a list of query string parameters to remove, which includes settings-updated.
  • It then writes some script into the page header to use window.history.replaceState to remove the query string from your browser’s URL bar.

    <link id="wp-admin-canonical" rel="canonical"
          href="http://example.com/wp-admin/admin.php?page=xyz">
    <script>
        if ( window.history.replaceState ) {
            window.history.replaceState( null, null,
                document.getElementById( 'wp-admin-canonical' ).href +
                    window.location.hash );
        }
    </script>
    

If you want to add your own arguments to the list that gets removed then you can hook removable_query_args.

Leave a Comment