GeneratorsAdminAdmin Notice

Admin Notice Generator

Notices that appear on the right screens, to the right people, and stay gone when dismissed — the AJAX handler and nonce included.

acme-setup-notice.php
Saved just now
Live preview

Acme Toolkit: add your API key to finish setting up.

Open settings

×
Shown on 2 screens
The notice
Where it shows
2 screens
Writes acme_setup_dismissed to user meta over AJAX — each person dismisses their own copy, permanently.
Behaviour
Dismissible
Adds is-dismissible so core prints the X button.
notice-alt styling
The flat variant core uses inside plugin table rows.
// Generated with WP CodeKit — powered by GrowQuest (https://growquest.io).
/**
 * Print the notice.
 */
function acme_notice() {
	if ( ! current_user_can( 'manage_options' ) ) {
		return;
	}

	$screen = get_current_screen();

	if ( ! $screen || ! in_array( $screen->id, array( 'dashboard', 'plugins' ), true ) ) {
		return;
	}

	if ( get_user_meta( get_current_user_id(), 'acme_setup_dismissed', true ) ) {
		return;
	}

	printf(
		'<div class="notice notice-warning is-dismissible" data-notice="acme_setup"><p><strong>%1$s</strong> %2$s</p><p><a href="%4$s" class="button button-primary">%3$s</a></p></div>',
		esc_html__( 'Acme Toolkit:', 'acme' ),
		esc_html__( 'add your API key to finish setting up.', 'acme' ),
		esc_html__( 'Open settings', 'acme' ),
		esc_url( admin_url( 'options-general.php?page=acme-toolkit' ) )
	);
}
add_action( 'admin_notices', 'acme_notice' );

/**
 * Send the dismissal back so it sticks. Printed only where the notice itself would appear.
 */
function acme_dismiss_script() {
	if ( ! current_user_can( 'manage_options' ) ) {
		return;
	}

	$screen = get_current_screen();

	if ( ! $screen || ! in_array( $screen->id, array( 'dashboard', 'plugins' ), true ) ) {
		return;
	}

	if ( get_user_meta( get_current_user_id(), 'acme_setup_dismissed', true ) ) {
		return;
	}

	$nonce = wp_create_nonce( 'acme_setup_dismissed' );
	?>
	<script>
	document.addEventListener( 'click', function ( event ) {
		var button = event.target.closest( '[data-notice="acme_setup"] .notice-dismiss' );

		if ( ! button ) {
			return;
		}

		window.fetch( ajaxurl, {
			method: 'POST',
			credentials: 'same-origin',
			headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
			body: new URLSearchParams( {
				action: 'acme_dismiss_notice',
				nonce: '<?php echo esc_js( $nonce ); ?>'
			} )
		} );
	} );
	</script>
	<?php
}
add_action( 'admin_footer', 'acme_dismiss_script' );

/**
 * Store the dismissal.
 */
function acme_dismiss() {
	check_ajax_referer( 'acme_setup_dismissed', 'nonce' );

	if ( ! is_user_logged_in() ) {
		wp_send_json_error( null, 403 );
	}

	update_user_meta( get_current_user_id(), 'acme_setup_dismissed', time() );

	wp_send_json_success();
}
add_action( 'wp_ajax_acme_dismiss_notice', 'acme_dismiss' );