April 16, 2014

WordPress: Anonymous PHP functions

Recently I wrote about my problem with WordPress editor and now I realize that I wanted to write also about something different - using anonymous functions in WordPress development - it's amazing how using of them can simplify your code (if you forget older PHP versions).

Compare these examples:

<?php
// Sets WordPress admin bar hidden.
// Old:
add_filter('show_admin_bar', '__return_false');
// New:
add_filter('show_admin_bar', function() { return false; });

// Activate widgets
// Old:
add_action('widgets_init',
     create_function('', 'return register_widget("Your_Widget_Class");')
);
// New:
add_action('widgets_init', function() {
    register_widget('Your_Widget_Class');
});

And of course that this can be used everywhere you're using function such add_action, add_filter etc.







No comments: