Passing arguments to a admin menu page callback?

Situation: I’m working on a plugin and I’m developing it as a class, everything worked fine until I run into this situation. I wanted to make things a bit cleaner and tried this..

class MyPlugin {
    function __construct() {
        add_action('admin_menu', array(&$this, 'myplugin_create_menus');
    }        

    //I don't want to write a function for every options page I create
    //so I prefer to just load the content from an external file.        
    function load_view($filename) {
        $view = require(dirname(__FILE__).'/views/'.$filename.'.php');
        return $view;
    }

    //Here is where the problem comes
    function myplugin_create_menus() {
        add_menu_page( 'Plugin name',
                       'Plugin name',
                       'manage_options',
                       'my-plugin-settings',
                       array(&$this, 'load_view') // Where do I specify the value of $filename??
                     );
    }

}#end of class

I’ve tried a bunch of different options but nothing works, maybe I’m in front of it but I can’t see it.

Of course this is a re-creation, I’ve prefixed all my functions and they are not exactly as I wrote here but I hope you got the idea of I’m asking for.

Thanks in advance.

P.D.: If you want to see the original source code I’ll be glad to paste it and give you the link.

5

You can’t pass an argument to the callback function. add_menu_page() adds it as an action handler, and admin.php fires the action, without any arguments.

I see two simple solutions to this problem. One is to store all filename in an array in your class, indexed by hook name. Then you can use this to look up what file you need to load (you can also store additional data in this array).

class WPSE16415_Plugin
{
    protected $views = array();

    function load_view() {
        // current_filter() also returns the current action
        $current_views = $this->views[current_filter()];
        include(dirname(__FILE__).'/views/'.$current_views.'.php');
    }

    function myplugin_create_menus() {
        $view_hook_name = add_menu_page( 'Plugin name',
            'Plugin name',
            'manage_options',
            'my-plugin-settings',
            array(&$this, 'load_view'),
        );
        $this->views[$view_hook_name] = 'options';
    }
}

The other is to skip the callback argument, so WordPress will include the file indicated by the slug name itself, as Brady suggests in his answer.

Leave a Comment