• Resolved Neil

    (@ademmeda)


    Hi,

    I started developing a plugin from scratch and I have a small problem with my setup.

    Firstly, here is the error I am getting:

    Warning: call_user_func_array() expects parameter 1 to be a valid callback, function ‘my_function’ not found or invalid function name in C:\…\wp-includes\plugin.php on line 405

    And here is my code:

    add_action( 'admin_menu', array( 'my_plugin', 'menu' ) );
    
    class my_plugin {
    
    	function menu() {
    		if ( current_user_can( 'manage_options' ) ) {
    			add_menu_page( 'Settings', 'Settings', 'manage_options', 'my-plugin', 'my_function' );
    		}
    	}
    
    	function my_function() {
    		include 'inc/settings.php';
    	}
    }
    
    $my_plugin = new my_plugin;

    I am new to PHP classes and I can’t see what is wrong.

    Thanks for any ideas.

Viewing 4 replies - 1 through 4 (of 4 total)
  • There are a couple problems.

    1. add_menu_page expects a single argument for the function (you’re using two). Should be array(class,function) or just function.
    2. you instantiate the class, but then hook to the static methods.

    I would also suggest that if you’re going to wrap your plugin in a class, keep everything (ie. add_action) inside the class.

    Here’s a quick suggestion, hope it helps.

    class my_plugin {
    
            function __construct() {
                add_action( 'admin_menu', array( &$this, 'menu' ) );
            }
    
    	function menu() {
    		if ( current_user_can( 'manage_options' ) ) {
    			add_menu_page( 'Settings', 'Settings', 'manage_options', array( &$this, 'my_function') );
    		}
    	}
    
    	function my_function() {
    		include 'inc/settings.php';
    	}
    }
    
    $my_plugin = new my_plugin;
    Thread Starter Neil

    (@ademmeda)

    Hi,

    Thanks for the reply, “$this” didn’t work and I found the answer on http://codex.wordpress.org/Function_Reference/add_submenu_page

    Now I have

    add_menu_page( 'Plugin Settings', 'Settings', 'manage_options', 'plugin-slug', array( __CLASS__, 'settings' ) );

    and it works.

    Sorry, I am new to all this, what does “you instantiate the class, but then hook to the static methods.” mean? Why should I keep everything in the plugin class? What problems could happen?

    Thanks a lot.

    $this does work, but only when you use the complete code I provided.

    There are no downsides to how you are writing your class. I’m simply stating you will run into troubles until you understand the basics of OOP in PHP. Pay particular attention to scoping.

    Thread Starter Neil

    (@ademmeda)

    Thanks for the link, I guess I should have started learning from that page.

Viewing 4 replies - 1 through 4 (of 4 total)
  • The topic ‘Not found or invalid function error’ is closed to new replies.