1

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()

1
  • just remove last 2 line of your code and you are done. Commented Sep 5, 2017 at 5:50

2 Answers 2

2

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') );
Sign up to request clarification or add additional context in comments.

3 Comments

ok. but, the callback function my_plugin_options() is not running.
@Steve OK, but that sounds like a different issue. Did this solve the problem you asked in your question? Regarding my_plugin_options, you will need to use $this for it also - just like in add_action - because you are using a class.
@Steve I've updated my answer for using $this in my_plugin_options
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.