How to pass parameters to admin_notices?
Question
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.
La solution
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." );
}
Autres conseils
Can be done much more straight forward:
$message = $name . ' has been upgraded.';
add_settings_error( 'my_admin_notice', 'my_admin_notice', $message, 'updated' );
Read more on https://developer.wordpress.org/reference/functions/add_settings_error/
Licencié sous: CC-BY-SA avec attribution
Non affilié à wordpress.stackexchange