Why does WordPress add_menu not work when seperated from Initial plugin page?

So I’m working on a very very basic plugin for WordPress. I copied the following from the internet a menu item plugin named menu.php

<?php

/*
Plugin Name: Test plugin
Description: A test plugin to demonstrate wordpress functionality
Author: Simon Lissack
Version: 0.1
*/
defined( 'ABSPATH' ) or die( 'No script kiddies please!' );

add_action('admin_menu', 'test_plugin_setup_menu');

function test_plugin_setup_menu(){
    add_menu_page( 'Test Plugin Page', 'Test Plugin', 'manage_options', 'test-plugin', 'test_init' );
}

function test_init(){
    echo "<h1>Hello World!</h1>";
}

?>

This works as expected but it’s a stand alone plugin. I currently have a different plugin

Read More
<?php

/*
Plugin Name: My plugin
Description: blah blah
Author: Me
Version: 0.1
*/
defined( 'ABSPATH' ) or die( 'No script kiddies please!' );

fun fun database work on register_activation_hook
?>

The problem is I’d like to have it all in one plugin not two I tried this and I deleted the commenting that made it register as a plugin in menu.php

/*
Plugin Name: My plugin
Description: blah blah
Author: Me
Version: 0.1
*/
defined( 'ABSPATH' ) or die( 'No script kiddies please!' );

include_once('menu.php');
fun fun database work
?>

Fatal error: Call to undefined function wp_get_current_user() in wp-includescapabilities.php on line 1387 and this is the error I get. However doing the following gives me the desired result

/*
Plugin Name: My plugin
Description: blah blah
Author: Me
Version: 0.1
*/
defined( 'ABSPATH' ) or die( 'No script kiddies please!' );

 add_action('admin_menu', 'test_plugin_setup_menu');

function test_plugin_setup_menu(){
    add_menu_page( 'Test Plugin Page', 'Test Plugin', 'manage_options', 'test-plugin', 'test_init' );
}

function test_init(){
    echo "<h1>Hello World!</h1>";
}

fun fun database work
?>

The reason I’d like to know how to get it to work using the include or require or at least know why I can’t is because I’m sure my plugin will grow and I would like to have it in a bunch of smaller easier for me to maintain files than one big initial file.

Thank you for your help ohh I’ve also tried

<?php

/*
Plugin Name: My plugin
Description: blah blah
Author: Me
Version: 0.1
*/
defined( 'ABSPATH' ) or die( 'No script kiddies please!' );

  //  add_action('plugins_loaded','load_menu');//didn't work same error
add_action('init','load_menu');//didn't work same error

function load_menu(){
    include_once('menu.php');
 }
fun fun database work
?>

Thanks again for any help

Related posts