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;' )
);
CodePudding user response:
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;
};
