This adds a dismissible admin notice to the WP admin with pure JavaScript. No jQuery or other dependencies. The admin notice will have a Dismiss icon just like the regular WP admin notices. When the icon is clicked, the message will go away.
This admin notice will have a blue left border which is given by the class notice-info
. You can change notice-info
on line 9.
- Use
notice-success
for a green left border. - Use
notice-error
for a red left border. - Use
notice-warning
for a yellow/orange left border.
In addition, you can add your own custom classes on line 9, if you like. They must be separated by a comma.
This is a JavaScript function, so it is reusable anytime you need to add an admin notice in your script. You would use it create an admin notice by calling the function like this:
myAdminNotice( 'Your message text' );
You would replace “Your message text” with your own message.
And here is the function:
/** * Create and show a dismissible admin notice */ function myAdminNotice( msg ) { /* create notice div */ var div = document.createElement( 'div' ); div.classList.add( 'notice', 'notice-info' ); /* create paragraph element to hold message */ var p = document.createElement( 'p' ); /* Add message text */ p.appendChild( document.createTextNode( msg ) ); // Optionally add a link here /* Add the whole message to notice div */ div.appendChild( p ); /* Create Dismiss icon */ var b = document.createElement( 'button' ); b.setAttribute( 'type', 'button' ); b.classList.add( 'notice-dismiss' ); /* Add screen reader text to Dismiss icon */ var bSpan = document.createElement( 'span' ); bSpan.classList.add( 'screen-reader-text' ); bSpan.appendChild( document.createTextNode( 'Dismiss this notice' ) ); b.appendChild( bSpan ); /* Add Dismiss icon to notice */ div.appendChild( b ); /* Insert notice after the first h1 */ var h1 = document.getElementsByTagName( 'h1' )[0]; h1.parentNode.insertBefore( div, h1.nextSibling); /* Make the notice dismissable when the Dismiss icon is clicked */ b.addEventListener( 'click', function () { div.parentNode.removeChild( div ); }); }
Optionally Add a Link in the Message
To add a link to the end of the message, insert the following code into line 19 above. This example will add a link that says, “Learn More.”
First, make these changes:
- On line 4, change ‘#’ to the URL that you want to link to.
- On line 5, change “Learn More” to your desired link text.
/* Add link in the message */ var a = document.createElement( 'a' ); a.setAttribute( 'href', '#' ); a.appendChild( document.createTextNode( 'Learn More' ) ); /* spaces */ p.appendChild( document.createTextNode( '\xa0 \xa0' ) ); p.appendChild( a );
sam john
November 10th, 2020 at 7:41 am
i have added this script in my new plugin smm-api and it is working fine