Steve
Steve

Reputation: 1672

Undefined add_menu_page() wordpress function

I am trying to write plugin with OOP approach.

class MySettingsPage
{
     public function __construct() {
        add_action( 'admin_menu', 'registration_plugin_menu' );
    }

public function registration_plugin_menu() {
    add_menu_page( 'Basic Registration Form', 'Basic Registration Plugin', 'manage_options', 'registration-plugin', 'my_plugin_options' );
}


public function my_plugin_options() {
        //callback function
  }
}

$settings = new MySettingsPage();
$settings->registration_plugin_menu();
$settings->my_plugin_options();

However, i am getting the error:

Uncaught Error: Call to undefined function add_menu_page()

Upvotes: 1

Views: 770

Answers (2)

FluffyKitten
FluffyKitten

Reputation: 14312

You need to call add_menu_page via a hook e.g. admin_menu. You do hook into admin_menu here:

add_action( 'admin_menu', array($this, 'registration_plugin_menu' ));

But you also call registration_plugin_menu directly here, which will try to run the add_menu_page function immediately - before WP is ready for it:

$settings->registration_plugin_menu();

You don't need that line - it will get called automatically in the constructor.

FYI, you will need to use $this in your add_action call in the constructor because you have it in a class.

Update:

You will also need to use $this in add_menu_page for my_plugin_options, e.g.

add_menu_page( 'Basic Registration Form', 'Basic Registration Plugin', 'manage_options', 'registration-plugin', array($this, 'my_plugin_options') );

Upvotes: 2

Vel
Vel

Reputation: 9342

Try this

class MySettingsPage
{
    public function __construct() {
    add_action( 'admin_menu', array($this, 'registration_plugin_menu' ));
    }

public function registration_plugin_menu() {
    add_menu_page( 'Basic Registration Form', 'Basic Registration Plugin', 'manage_options', 'registration-plugin', array($this,'my_plugin_options') );
}


public function my_plugin_options() {
    //callback function
  }
}

$settings = new MySettingsPage();

enter image description here

Upvotes: 1

Related Questions