skip to Main Content

Our host updated PHP and caused some of our stuff to not work. I understand create_function isnt valid any longer but I am having a hard time converting this. Can someone please help?

add_filter('single_post_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;' )
);

2

Answers


  1. You just need to create an anonymous function instead:

    // uses a static function to pass $the_template to the filter.
    add_filter( 'single_post_template', static function ( $the_template ) {
    
        // Uses a variable instead to hold the categories.
        $cats = get_the_category();
    
        foreach ( $cats as $cat ) :
            if ( get_template_directory() . '/single-' . $cat->slug . '.php' ) :
                return get_template_directory() . '/single-' . $cat->slug . '.php';
            endif;
        endforeach;
    
        return $the_template;
    });
    
    Login or Signup to reply.
  2. Try the following steps:

    1. If you are using an inbuilt theme update it.
    2. If you are using a custom theme replace the code.

    In WordPress, replace create_function() with an Anonymous function as below:

    add_filter('single_template', function ($single) {
        global $wp_query, $post;    
    
        foreach((array)get_the_category() as $cat) :
    
            // single posts template based on category slug
            if(file_exists( get_stylesheet_directory() . '/single-' . $cat->slug . '.php'))
                $single =  get_stylesheet_directory() . '/single-' . $cat->slug . '.php';
    
            //else load single.php  
            elseif(file_exists( get_stylesheet_directory() . '/single.php'))
                $single =  get_stylesheet_directory() . '/single.php';
    
        endforeach;
    
        return $single;
    });
    

    For more details about create_function(), go to this link

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search