In notices inside the block editor, you can define actions that are displayed below the notice. By default, these cannot be open in a new tab. But what if you want to?

The builtin notice system in the block editor allows you to create info, error, success and warning notices without creating a whole system yourself. Additionally, you can attach a list of actions to them. They will be displayed below the actual notice and render as buttons. And they also work similar to the button component in general. However, there is no support for the target attribute within the notice system.

Another problem is the styling when you want to display the button as a plain link, because simply adding the variant: 'link' to the action does not create a link button by default if no url is provided (which cannot be used here, since then the link will never open in a new tab). Instead, it is forcefully changed to variant secondary and thus renders a button.

Mitigate the target problem

To workaround the problem with no explicit target attribute, we can use the onClick parameter and use a window.open() with the second parameter as _blank in order to create a link that opens in a new tab.

Correct styling for plain links

Since the default is to render a secondary styled button in this case, we need to remove these classes. This can be done by setting noDefaultClasses to true, together with variant being link. This then will properly render the button as a plain link.

Example

As an example, this is what a success notice looks like with an action as plain link, that opens in a new tab:

createSuccessNotice( __( 'Success notice.', 'my-plugin' ), {
	actions: [
		{
			label: __( 'Go to page (opens in a new tab) ↗', 'my-plugin' ),
			noDefaultClasses: true, // make sure link variant is used even without URL
			onClick: () => window.open( '#', '_blank' ),
			variant: 'link',
		},
	],
} );
Code language: JavaScript (javascript)

Please make sure to notify the user about the link being opened in a new tab as in the example for improved accessibility if you force it like that.

Reposts

Leave a Reply

Your email address will not be published. Required fields are marked *

To respond on your own website, enter the URL of your response which should contain a link to this post's permalink URL. Your response will then appear (possibly after moderation) on this page. Want to update or remove your response? Update or delete your post and re-enter your post's URL again. (Learn more about webmentions)