PHP: Replace this create_function

531 Views Asked by At

this old php script I pasted from the internet is no longer supported. create_function no longer works and I would like to replace it. However I'm not capable of finding a modern solution. My PHP skills are too bad to even understand how this used to work. Does anyone know a quick fix? I would greatly appreciate it!

//Gets post cat slug and looks for single-[cat slug].php and applies it
add_filter('single_template', create_function(
    '$the_template',
    'foreach( (array) get_the_category() as $cat ) {
        if ( file_exists(TEMPLATEPATH . "/single-{$cat->slug}.php") )
        return TEMPLATEPATH . "/single-{$cat->slug}.php"; }
    return $the_template;' )
);
1

There are 1 best solutions below

7
LSerni On BEST ANSWER

This type of conversion is actually extremely simple because the strings involved are constants (note the single quotes). So, there is nothing going in or out of the function except its parameters.

That means that what you have is a normal, ordinary function.

So:

$newFunction = function($the_template) {
    foreach((array)get_the_category() as $cat) {
        if (file_exists(TEMPLATEPATH . "/single-{$cat->slug}.php")) {
            return TEMPLATEPATH . "/single-{$cat->slug}.php";
        }
    }
    return $the_template;
};

add_filter('single_template', $newFunction);

I think this should work too (only minimal changes):

$newFunction = function($theTemplate) {
    foreach(get_the_category() as $cat) {
        $php = TEMPLATEPATH . "/single-{$cat->slug}.php";
        if (file_exists($php)) {
            return $php;
        }
    }
    return $theTemplate;
};

Update

You do not even need to declare the function, but can use an anonymous function: notice that the anonymous body is simply the second parameter to the old create_function, while the first parameter specified the anonymous parameters.

add_filter(
    'single_template',
    function($theTemplate) {
         foreach(get_the_category() as $cat) {
         $php = TEMPLATEPATH . "/single-{$cat->slug}.php";
         if (file_exists($php)) {
            return $php;
         }
         return $theTemplate;
    }
);