更新 WordPress 中的 add_filter() 内的 create_function()。

huangapple go评论55阅读模式
英文:

Updating create_function Inside WordPress add_filter()

问题

只更新了另一个WordPress网站,从PHP 7.4升级到8.1,并需要更新不推荐使用的create_function。以下是旧代码:

add_filter( 'loop_shop_per_page', create_function( '$cols', 'return '.$sp_products_per_page.';' ), 20 );

我将其更新为:

add_filter( 'loop_shop_per_page', function($cols) { return $sp_products_per_page; }, 20);

但似乎仍然无法正常工作。这个语法正确吗?

英文:

Just updated another WordPress site from PHP 7.4 to 8.1 and needed to update the deprecated create_function. Here's the old code:

add_filter( 'loop_shop_per_page', create_function( '$cols', 'return '.$sp_products_per_page.';' ), 20 );

I updated it to:

add_filter( 'loop_shop_per_page', function($cols) { return $sp_products_per_page; }, 20);

But it still doesn't seem to be working correctly. Is this syntax correct?

答案1

得分: 1

从你拥有的两个函数来看,我认为这是一个作用域的问题。

$sp_products_per_page 在全局作用域中声明/存在,因为你使用了一个匿名函数,所以它无法从函数作用域中访问到。
所以你需要将代码修改为:

add_filter( 'loop_shop_per_page', function($cols) use ($sp_products_per_page) { return $sp_products_per_page; }, 20);

稍微调整一下格式,我们得到了以下代码:

add_filter( 'loop_shop_per_page', function($cols) use ($sp_products_per_page) {
    return $sp_products_per_page;
}, 20);
英文:

From the two functions you have, I assume it's a scope issue.

$sp_products_per_page is declared/exists on a global scope, and because you use an anonymous function, it's not accessible from the function scope.
So instead of

add_filter( 'loop_shop_per_page', function($cols) { return $sp_products_per_page; }, 20);

You'll need to add a use keyword

add_filter( 'loop_shop_per_page', function($cols) use ($sp_products_per_page) { return $sp_products_per_page; }, 20);

A bit of formatting and we have this

add_filter( 'loop_shop_per_page', function($cols) use ($sp_products_per_page) {
    return $sp_products_per_page;
}, 20);

huangapple
  • 本文由 发表于 2023年6月12日 16:08:15
  • 转载请务必保留本文链接:https://go.coder-hub.com/76454674.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定