如何将参数传递给ADMIN_NOTICES?

时间:2016-04-22 作者:Aley

因此,有以下情况。

我需要在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\' ) );
如何填充$name?

我考虑以下解决方案:

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\' ) );
第2条:

$name = \'John Doe\';

add_action(\'admin_notices\', function() use ($name){ 
    echo $name . \' has been upgraded.\'; 
});
不知何故,我不喜欢两者,因为1号需要$name 待填充class 宽,因此可能会导致混淆,2号至少需要PHP 5.3。

2 个回复
最合适的回答,由SO网友:TheDeadMedic 整理而成

我认为更好的实现应该是“消息”类,例如:

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 );
    }
}
这允许您在呈现之前随时实例化消息:

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

SO网友:RavanH

可以做得更直接:

$message = $name . \' has been upgraded.\';

add_settings_error( \'my_admin_notice\', \'my_admin_notice\', $message, \'updated\' );
了解更多信息https://developer.wordpress.org/reference/functions/add_settings_error/

相关推荐

WP_COMMENTS表真的很大,正在慢慢加载/wp-admin/dit-Comments.php

我们的wp\\u注释有数百万行。当我们加载时/wp/wp-admin/edit-comments.php 它将超时。看看mysql,这个简单的查询需要很长时间SELECT wp_comments.comment_ID FROM wp_comments WHERE ( ( comment_approved = \'0\' OR comment_approved = \'1\' ) ) AND comment_type IN (\'pingback\', \'trackback\')&