我正在创建一个插件。但当我想打电话给add_action(\'admin_notices\',\'my_test_notice_1\');
在函数内部,它不工作。
我需要打电话给add_action(\'admin_notices\',\'my_test_notice_1\')
在我的职能范围内。我该怎么做。-感谢您的回答。
<?php
/*
* Plugin Name: Test Plugin
* Description: Testin the plugin description
* Version: 1.0.0
* Author: Shafiq Suhag
* Author URI: https://roobnet.com/
* License: GPLv2 or later
* License URI: https://www.gnu.org/licenses/gpl-2.0.html
* Text Domain: rsms
* Domain Path: /languages
*/
function test_plugin_admin_menu()
{
add_menu_page(__(\'Testing Page \', \'rses\'), __(\'Testing Page\', \'rses\'), \'activate_plugins\', \'testing_plugin\', \'testing_plugin_cb_function\',\'dashicons-businessman\');
function testing_plugin_cb_function(){
// Admin Notice 2 : This is not working
add_action(\'admin_notices\', \'admin_notice_2\');
function admin_notice_2(){
echo \'<h1> admin_notice_1 is printed on the page </h1>\';
}
}
// Admin Notice 1 - This is working
add_action(\'admin_notices\', \'admin_notice_1\');
function admin_notice_1(){
echo \'<h1> admin_notice_1 is printed on the page </h1>\';
}
}
add_action(\'admin_menu\', \'test_plugin_admin_menu\');
最合适的回答,由SO网友:CodeMascot 整理而成
这是因为钩子射击的顺序。钩子实际上是从数组中加载的(have a look) 哪里admin_notices
在之前执行add_menu_page
被调用。
现在要在您的管理页面中显示消息,您可以查看global $pagenow
和页面获取变量$_GET[\'page\']
使用if
调整并打印您的邮件。如下所示-
add_action( \'admin_menu\', \'test_plugin_admin_menu\' );
function test_plugin_admin_menu () {
add_menu_page(
__(\'Testing Page \', \'rses\'),
__(\'Testing Page\', \'rses\'),
\'activate_plugins\',
\'testing_plugin\',
\'testing_plugin_cb_function\',
\'dashicons-businessman\'
);
}
function testing_plugin_cb_function () {
// Do your magic here
}
add_action( \'admin_notices\', \'admin_notice_1\' );
function admin_notice_1 () {
global $pagenow;
if ( \'admin.php\' === $pagenow && \'testing_plugin\' === $_GET[\'page\'] ) {
echo \'<h1> admin_notice_1 is printed on the page </h1>\';
}
}
顺便说一下,嵌套函数是一件很糟糕的事情,所以我在这里放了一个
refactored version of your code. 请在投入生产前进行测试。
希望这有帮助。