You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PHP升级致WordPress中create_function报错,请求代码转换协助

替代废弃的create_function兼容PHP新版本的写法

原代码依赖的create_function()函数在PHP 7.2及以上版本已被废弃,PHP 8.0+更是直接移除了这个函数,所以需要改成现代PHP支持的匿名函数写法,转换后的代码如下:

add_filter('single_post_template', function($the_template) {
    foreach( (array) get_the_category() as $cat ) {
        $template_path = get_template_directory() . "/single-{$cat->slug}.php";
        if ( file_exists($template_path) ) {
            return $template_path;
        }
    }
    return $the_template;
});

几个关键改动说明:

  • 直接用PHP匿名函数(闭包)替换create_function(),这是当前PHP官方推荐的回调写法,语法更直观,也避免了废弃函数的兼容性问题
  • 将模板路径提取为单独变量$template_path,让代码更易读和维护
  • 把旧版WordPress常量TEMPLATEPATH替换为get_template_directory()函数,这是WordPress官方更推荐的用法,兼容性更强
  • 给if语句补全了大括号,遵循代码规范,避免因缩进导致的逻辑错误

内容的提问来源于stack exchange,提问作者Brad Wickwire

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.15 17:42:05