How to pass parameters to admin_notices?

So there is the following case.

I need to display a name inside of admin_notices.

class MyPlugin_Admin {
    public static function render_admin_notice() {
        echo $name . ' has been upgraded.';
    }
}

add_action( 'admin_notices', array( 'MyPlugin_Admin', 'render_admin_notice' ) );

How to populate $name?

I thougth of following solutions:

No. 1:

class MyPlugin_Admin {

    public static $name;

    public static function render_admin_notice() {
        echo self::$name . ' has been upgraded.';
    }
}

MyPlugin_Admin::$name="John Doe";

add_action( 'admin_notices', array( 'MyPlugin_Admin', 'render_admin_notice' ) );

No. 2:

$name="John Doe";

add_action('admin_notices', function() use ($name){ 
    echo $name . ' has been upgraded.'; 
});

I don’t like both somehow, since No. 1 requires $name to be populate class wide and therefor might lead to confusion and No. 2 requires at least PHP 5.3.

2

I think a better implementation would be a “message” class e.g.:

class WPSE_224485_Message {
    private $_message;

    function __construct( $message ) {
        $this->_message = $message;

        add_action( 'admin_notices', array( $this, 'render' ) );
    }

    function render() {
        printf( '<div class="updated">%s</div>', $this->_message );
    }
}

This allows you to instantiate the message at any time prior to rendering:

if ( $done ) {
    new WPSE_224485_Message( "$name has been upgraded." );
}

Leave a Comment