1

I would like to understand why I cannot use [ $this, 'function' ] within it's own class.

This works:

init.php

if ( is_admin() )
{
    require ( dirname ( __FILE__ ) . '/inc/admin/Admin.php' );
    add_action('admin_menu', ['Mango\Admin', 'adminMenu'] );
}

/inc/admin/Admin.php - Version 1 (working)

<?php namespace Mango;

class Admin
{
    public function adminMenu()
    {
    //this is the main item for the menu
    add_menu_page(
        'Mango Settings', //page title
        'Mango Settings', //menu title
        'manage_options', //capabilities
        'mango-settings', //menu slug
        [ 'Mango\Admin', 'settingsPage' ] // LOOK HERE *******
    );
    }

    public function settingsPage()
    {
        echo 'This is a test';
    }
}

/inc/admin/Admin.php - Version 2 (not working)

<?php namespace Mango;

class Admin
{
    public function adminMenu()
    {
    //this is the main item for the menu
    add_menu_page(
        'Mango Settings', //page title
        'Mango Settings', //menu title
        'manage_options', //capabilities
        'mango-settings', //menu slug
        [ $this, 'settingsPage' ] // LOOK HERE *******
    );
    }

    public function settingsPage()
    {
        echo 'This is a test';
    }
}

Error Message: Warning: call_user_func_array() expects parameter 1 to be a valid callback, first array member is not a valid class name or object in /.../wp-includes/plugin.php on line 429

I don't really understand why I cannot register [ $this, 'settingsPage' ] with the add_menu_page hook. Surely the working version 1 is needlesly creating a 2nd copy of the Mango\Admin class?

Can anybody shed some light on this for me please?

1 Answer 1

2

Maybe a little late for an answer, but it probably would help others too;

If the function is a member of a class within the plugin it should be referenced as array( $this, 'function_name' )

http://codex.wordpress.org/Function_Reference/add_menu_page

class Admin
{
    public function adminMenu()
    {
    //this is the main item for the menu
     add_menu_page(
        'Mango Settings', //page title
        'Mango Settings', //menu title
        'manage_options', //capabilities
        'mango-settings', //menu slug
        array( $this, 'settingsPage' ) // LOOK HERE *******
    );
    }

    public function settingsPage()
    {
        echo 'This is a test';
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for having the foresight to post the correct answer to an old question. Your answer is over 6 years old and it still helped me!

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.