Support » Developing with WordPress » Admin_init not working in submenu page

  • I’ve a plugin divided into multiple pages and files based on classes.

    The base file (linked from plugin main file) contains code for menu and submenu pages and provides wordpress with their respective files in a subfolder.

    The problem is, that the admin_init hook isn’t working in the submenu page (trying to save values from a form submitted in submenu page).

    The main page looks like (the admin_init hook works fine if used in this file class itself):

    class MyPlugin {
    
        public function __construct(){
            add_action( 'admin_menu', array( $this, 'add_menu' ) );
        }
    
        public function add_menu() {
            add_menu_page(
                'My Plugin',
                'My Plugin',
                'manage_options',
                MY_PLUGIN_DIR.'/inc/admin/class-my-plugin-home.php',
                '',
                'dashicons-yes',
                89
            );
    
            add_submenu_page(
                MY_PLUGIN_DIR.'/inc/admin/class-my-plugin-home.php',
                'Submenu page',
                'Submenu page',
                'manage_options',
                MY_PLUGIN_DIR.'/inc/admin/class-my-plugin-submenu.php',
                ''
            );
        }
    }

    While the submenuclass-my-plugin-submenu.php file looks like:

    function checkit(){
    
        echo "This code is not working or showing (just for example)";
    }
    
    add_action( 'admin_init', 'checkit' );
Viewing 3 replies - 1 through 3 (of 3 total)
  • Sounds like the code for the submenu is not loaded in all cases, so it can’t do the add_action.
    Put all the add_action calls into the main plugin file.

    Thread Starter nabtron

    (@nabtron)

    Please check this code to understand the issue i’m having please and suggest the best solution: https://github.com/nabtron/wp-admin-init-test-plugin

    Moderator bcworkz

    (@bcworkz)

    Your first problem is passing a file path as the callable parameter. You need to pass a callable function name. You can include or require your file from that function.

    You will then find, once your file is referenced that way, that the add_action() call is called too late. By the time your submenu plugin file executes, the “admin_init” action had already fired. Joy is correct, you should call add_action() from your main plugin file, or at least among code that executes when your plugin is loaded.

    The above comments also apply to the initial menu page as well.

Viewing 3 replies - 1 through 3 (of 3 total)
  • The topic ‘Admin_init not working in submenu page’ is closed to new replies.