Question

I am creating a plugin . But when I trying to call the add_action('admin_notices','my_test_notice_1'); inside a function its not working.

I need to call the add_action('admin_notices','my_test_notice_1') inside my function . How can I do it. - Thanks advance for your answer.

<?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'); 
Was it helpful?

Solution

Well, this is happening because of hook firing sequence. Hooks actually get loaded from an array(have a look) where admin_notices executes before add_menu_page gets called.

Now to show you message in your admin page you can check global $pagenow and the page GET variable by $_GET['page'] with an if condition and print your message. Like below-

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>';
    }
}

By the way, nested functions are quite a bad thing, so I'm putting here a refactored version of your code. Please test it before putting it in production.

Hope that helps.

Licensed under: CC-BY-SA with attribution
Not affiliated with wordpress.stackexchange
scroll top