How we store error/success messages to the next page

I am working on site. I uses some custom error/success messages for front end form but currently it display messages to on same page, But as soon as I refresh the page or redirect the user to next page messages not save. To save the success messages I use the code

$success = __('You have successfully Login.', 'frontendprofile');

And for the error messages I use the default varible that is $error. How can save them the for next page or for when if I refresh the page?

Related posts

Leave a Reply

1 comment

  1. You could save the messages in a $_SESSION variable. This way, the values will be preserved untill you decide to remove them again.

    function save_message( $type, $message = '' ) {
        $_SESSION['messages'][$type] = $message;
    }
    
    function get_messages() {
        $return = '';
    
        if ( isset( $_SESSION['messages'] ) && is_array( $_SESSION['messages'] ) ) {
            foreach( $_SESSION['messages'] as $type => $message ) {
                $return .= sprintf( '<p class="%1$s">%2$s</p>', $type, $message );
            }
        }
    
        if ( strlen( $return ) > 0 )
            return $return;
    
        return false;
    }
    
    function clean_messages( $type = false ) {
        if ( ! $type )
            $_SESSION['messages'] = array();
    
        else
            unset( $_SESSION['messages'][$type];
    }
    

    Something like this.
    You can use it like follows:

    save_message( 'success', __( 'You have successfully Login.', 'frontendprofile' ) );
    
    if ( $messages = get_messages() ) {
        echo $messages;
    
        clean_message('success');
    }