Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

When my plugin is activated, I would like to add a new menu item. Here is my code:

class My_Plugin {
  function __construct() {
    register_activation_hook(__FILE__, array($this, 'install'));
  }

  function install() {
    add_action('admin_menu', array($this, 'add_menu_item'));
  }

  public function add_menu_item() {
    add_menu_page(...);
  }
}

$my_plugin = new My_Plugin();

Unfortunately, it doesn't work. I notice that install is called, but add_menu_item isn't.

What would be the proper way to do this?

share|improve this question
add comment

1 Answer

up vote 2 down vote accepted

Plugins are activated in a sandbox and their output is captured to check for errors, and redirect if activation was successful. Adding something in an activation hook will cause it to run once in that "invisible" sandbox on activation, and that's it.

When you add an action, you're only adding it for that request, if you want your menu item to be visible on every admin page load, the add_action should be moved to the __construct function.

share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.