【问题标题】:PHP: Replace this create_functionPHP:替换这个 create_function
【发布时间】:2022-01-07 20:15:14
【问题描述】:

不再支持我从 Internet 粘贴的这个旧 php 脚本。 create_function 不再有效,我想替换它。但是我无法找到现代解决方案。我的 PHP 技能太糟糕了,甚至无法理解它过去是如何工作的。有谁知道快速修复?我将不胜感激!

//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;' )
);

【问题讨论】:

    标签: php deprecated create-function


    【解决方案1】:

    这种类型的转换实际上非常简单,因为涉及的字符串是常量(注意单引号)。所以,除了参数之外,没有任何东西进出函数。

    也就是说,你拥有的是一个普通的、普通的函数。

    所以:

    $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);
    

    我认为这也应该有效(只有最小的更改):

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

    更新

    你甚至不需要声明函数,但可以使用 anonymous 函数:注意匿名主体只是旧 create_function 的第二个参数,而第一个参数指定了匿名参数。

    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;
        }
    );
    

    【讨论】:

    • 亲爱的LSerni,非常感谢您的评论这对我非常有帮助!祝福你 :) - (对于所有想知道的人 - 第二个代码 sn-p 有效,当在末尾添加此代码时: add_filter('single_template', $newFunction);
    • 我有另一段代码在其中发生了函数。你能帮我翻译一下吗? add_action( 'widgets_init', create_function('', 'return register_widget("FreigeistRandomGalleryWidget");') );
    • @Foolix 原理相同;这个 newFunction2() 不带任何参数。函数的主体是第二个字符串。当 create_functions 的参数是单引号字符串时,转换很简单。
    • 感谢您的评论。我用它做了这个,但它不会起作用。我错过了什么? add_action( 'widgets_init', function() { return register_widget("FreigeistRandomGalleryWidget"); } ); PS:非常感谢您的帮助!
    • @Foolix 你做得完全正确。它应该工作。除非 register_widget 函数依赖于公共范围......?但这太疯狂了。这是任何机会WordPress吗?将 WordPress 安装更新到最新版本不是更好吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-11-02
    • 1970-01-01
    • 1970-01-01
    • 2011-09-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多