Quite a while ago, I grew tired of trying to come up with new and creative ways to display simple, one-time messages to users without crazy amounts of code for something that was frequently as trivial as “Saved!”.
Sessions are the obvious solution, however, without a single function that could both generate, AND display the messages, it still wasn’t any better. And as usual, where there’s a will, and some code- there’s a way!
Get Best Multi-Purpose WordPress Theme
Before we get started, make sure that a session is started, otherwise a) no message will be displayed, and b) super fun headers already sent messages.
//Ensure that a session exists (just in case)
if( !session_id() )
{
session_start();
}
//Actual function
/**
* Function to create and display error and success messages
* @access public
* @param string session name
* @param string message
* @param string display class
* @return string message
*/
function flash( $name = '', $message = '', $class = 'success fadeout-message' )
{
//We can only do something if the name isn't empty
if( !empty( $name ) )
{
//No message, create it
if( !empty( $message ) && empty( $_SESSION[$name] ) )
{
if( !empty( $_SESSION[$name] ) )
{
unset( $_SESSION[$name] );
}
if( !empty( $_SESSION[$name.'_class'] ) )
{
unset( $_SESSION[$name.'_class'] );
}
$_SESSION[$name] = $message;
$_SESSION[$name.'_class'] = $class;
}
//Message exists, display it
elseif( !empty( $_SESSION[$name] ) && empty( $message ) )
{
$class = !empty( $_SESSION[$name.'_class'] ) ? $_SESSION[$name.'_class'] : 'success';
echo '
.$class.‘” id=”msg-flash”>’.$_SESSION[$name].‘
‘
;
unset($_SESSION[$name]);
unset($_SESSION[$name.'_class']);
}
}
}
//Set the first flash message with default class
flash( 'example_message', 'This content will show up on example2.php' );
//Set the second flash with an error class
flash( 'example_class', 'This content will show up on example2.php with the error class', 'error' );
//Displaying the messages
<?php flash( 'example_message' ); ?>
<?php flash( 'example_class' ); ?>
You can download the source from here