Skip to content

Instantly share code, notes, and snippets.

@betweenbrain
Last active July 17, 2022 18:16
Show Gist options
  • Save betweenbrain/600babea1558a3d6520e8ab36be7573d to your computer and use it in GitHub Desktop.
Save betweenbrain/600babea1558a3d6520e8ab36be7573d to your computer and use it in GitHub Desktop.
WordPress Flash Messaging
<?php
/**
* Triggers validation when a post is saved.
*/
add_action(
'save_post',
'validate_post',
10,
3
);
/**
* Post validation.
*/
function validate_post( $id = null, $post = null, $update ) {
if ( wp_is_post_autosave( $post_ID ) ) {
return;
}
// Do not validate new posts.
/*
if ( ! $update ) {
return;
}
*/
// Prevent multiple executions.
if ( did_action( 'save_post' ) > 1 ) {
return;
}
// Validation logic goes here.
set_message( 'This is a vendor: ' . microtime( true ) );
}
/**
* Triggeras the display of admin notices.
*/
add_action(
'admin_notices',
function () {
check_messages();
}
);
/**
* Checks for admin notices.
*/
function check_messages() {
$msgs = json_decode( get_messages(), true );
if ( $msgs ) {
foreach ( $msgs as $msg ) {
?>
<div class="notice notice-success is-dismissible">
<p><?php echo $msg; ?></p>
</div>
<?php
}
}
delete_transient( 'my-custom-notices' );
}
/**
* Gets admin notices.
*/
function get_messages() {
return get_transient( 'my-custom-notices' );
}
/**
* Sets admin notices.
*/
function set_message( $msg ) {
$msgs = json_decode( get_messages(), true );
$msgs[] = $msg;
set_transient( 'my-custom-notices', json_encode( $msgs ) );
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment