将变量传递给wordpress过滤器中的匿名函数

jho*_*on4 3 php wordpress anonymous function

我试图覆盖一个在wordpress中创建SEO标题的插件.过滤器完成工作,但我需要动态创建标题.所以我创建标题然后将其传递给匿名函数.我可以有另一个功能,创建标题,这肯定会更清洁......

这有效

function seo_function(){

 add_filter('wpseo_title', function(){
        return 'test seo title';
    });

}
Run Code Online (Sandbox Code Playgroud)

事实并非如此

function seo_function(){

//create title above
$title="test seo title";


    add_filter('wpseo_title', function($title){
        return $title;
    });

}
Run Code Online (Sandbox Code Playgroud)

谢谢你的帮助

不使用匿名函数示例 - 这可行,但我仍然无法传递变量,我必须重复代码来创建标题.

function seo_function(){

//create title above
$title="test seo title";


    add_filter('wpseo_title', 'seo_title');

}

function seo_title(){

$title="test";

return $title;

}
Run Code Online (Sandbox Code Playgroud)

fux*_*xia 12

使用use关键字将变量传递到闭包范围:

$new_title = "test seo title";

add_filter( 'wpseo_title', function( $arg ) use ( $new_title ) {
    return $new_title;
});
Run Code Online (Sandbox Code Playgroud)

函数($ arg)中的参数将由apply_filters()调用发送,例如另一个插件,而不是您的代码.

另请参阅:将参数传递给过滤器和操作功能