gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 00:02:50 25 4
gpt4 key购买 nike

我正在尝试覆盖在 wordpress 中创建 SEO 标题的插件。过滤器可以完成工作,但我需要动态创建标题。所以我创建了标题,然后将它传递给一个匿名函数。我可以有另一个创建标题的函数,这样肯定会更干净......

这行得通

function seo_function(){

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

}

这不是

function seo_function(){

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


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

}

感谢您的帮助

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

函数 seo_function(){

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


add_filter('wpseo_title', 'seo_title');

}

function seo_title(){

$title="test";

return $title;

}

最佳答案

使用 use 关键字将变量传递到闭包作用域中:

$new_title = "test seo title";

add_filter( 'wpseo_title', function( $arg ) use ( $new_title ) {
return $new_title;
});

function($arg) 中的参数将由 apply_filters() 调用发送,例如其他插件,而不是您的代码。

另请参阅:Passing a parameter to filter and action functions

关于php - 将变量传递给 wordpress 过滤器中的匿名函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17907951/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com