When working in Javascript anonymous functions are used alot in callbacks. Recently when I have been trying out in WordPress plugin development I see alot of places where closures could be applied, but aren’t. For example:

For example, consider the callable parameter to this add_admin_menu function:

public function add_plugin_admin_menu() {
    add_menu_page(
         ... 
         array($this, 'display_plugin_setup_page'), 
         ... 
    );
}

public function display_plugin_setup_page() {
    include_once( 'partials/wp-cbf-admin-display.php' );
}

This could be written as:

public function add_plugin_admin_menu() {
    add_menu_page(
        ... 
        function () {
            include_once( 'partials/wp-cbf-admin-display.php' );
        }, 
        ... 
    );
}

//No need for a additional named public function

This pattern can also be applied to the large amount of actions/filters which often are added as a named function. Can someone explain to me if there is a drawback with my code suggestion above.

Read more here: Closures in WordPress Plugin Development


Solution:

If you know the solution of this issue, please leave us a reply in Comment section, to update the question.


Wordpress related questions and answers: