I'm developping a little plugin but I'm stuck when I tried to display Exception or success message after posting in a form.

Here is my code:

class Parametres_Plugin

public function __construct()
    add_filter('wp_title', array($this, 'modify_page_title'), 20) ;

    register_activation_hook(__FILE__, array('Parametres_Plugin', 'install'));
    register_uninstall_hook(__FILE__, array('Parametres_Plugin', 'uninstall'));

    add_action('admin_menu', array($this, 'addAdminMenu'));
    add_action('admin_menu', array($this, 'addAdminSousMenu'), 20);
    add_action('wp_loaded', array($this, 'saveParametre'));
   ... Other things ...

public function saveParametre(){


   ... Do something ...
      echo 'Sucess';
      echo 'Failed';
        } catch (Exception $e){
            echo 'Erreur: '.$e->getMessage()."\n";

But if I do like this my message is displayed at the begining of the code and not at the begining of my form. What I have to do to get this?

I tought to put my string in a var session, display it if exist in the form and unset it after. But I'm sure I'm missing something.

Thanks in advance !

  • Put it in a global variable, global $my_message; $my_message = 'success!!'; and in the top of your form call this: global $my_message; if ( isset($my_message) ) echo esc_attr($my_message), can be a simple solution
    – Ismail
    Nov 10, 2016 at 0:16
  • I didn't think to use global. It works very well. Thanks Samuel !
    – RomainA111
    Nov 10, 2016 at 12:49

1 Answer 1


As per the comments, using global variables is the suitable solution as you are seeking to store custom messages from the headers which will be displayed later with the markup, and using sessions would just result in extra code and extra memory usage (performance) while you can keep things simple.

If you print any message from your class, it will be printed on the top because yet WordPress hasn't started output.

Try this:

public function saveParametre()
    global $my_plugin_message;
    try {
    #... Do something ...
        if ($var) {      
            $my_plugin_message = 'Sucess';
        } else {
            $my_plugin_message = 'Failed';
    } catch (Exception $e) {
        $my_plugin_message = 'Erreur: '.$e->getMessage()."\n";

Now check for the global var $my_plugin_message while outputting your form:

<!-- form elements -->
<?php global $my_plugin_message;
if ( isset( $my_plugin_message ) ) : ?>
  <?php echo esc_attr( $my_plugin_message ); ?>
<?php endif; ?>
<!-- .. -->

That's one of the many advantages of global variables. Glad it helped.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.