phpcompatibilityphp-5.3anonymous-functionphp-5.2

How to rewrite this Anonymous Function code to work with PHP versions before 5.3?


I've added this small function to stop WordPress from checking for updates. However in PHP version less than PHP 5.3 anonymous functions don't work. I don't actually understand the purpose of an anonymous function in the code below so would rather ask here - how do I rewrite this code to work with PHP version before 5.3?

$func = function($a){
    global $wp_version;
    return (object) array(
        'last_checked' => time(),
        'version_checked' => $wp_version,
    );
};
add_filter('pre_site_transient_update_core', $func);
add_filter('pre_site_transient_update_plugins', $func);
add_filter('pre_site_transient_update_themes', $func);

Solution

  • You can use create_function which has been around since PHP 4.

    $func = create_function(
        '$a',
        'global $wp_version; return (object)array("last_checked" => time(), "version_checked" => $wp_version);'
    );
    
    add_filter('pre_site_transient_update_core', $func);
    add_filter('pre_site_transient_update_plugins', $func);
    add_filter('pre_site_transient_update_themes', $func);
    

    Anonymous function in WordPress are bad practice however. The nice thing about hooks is that the end user (or just someone other than the plugin/theme author) can remove the callbacks if they want. You can't do that with an anonymous function unless you keep a reference to it around some place. In this case, it would probably be better to just use a real function.

    function so19590942_check_version($a)
    {
        global $wp_version;
        return (object) array(
            'last_checked' => time(),
            'version_checked' => $wp_version,
        );
    }
    
    add_filter('pre_site_transient_update_core', 'so19590942_check_version');
    add_filter('pre_site_transient_update_plugins', 'so19590942_check_version');
    add_filter('pre_site_transient_update_themes', 'so19590942_check_version');
    

    Which lets another plugin/theme author or end user do something like...

    remove_filter('pre_site_transient_update_core', 'so19590942_check_version');
    

    If they don't like what you've done in so19590942_check_version.