PHP7.2中create_function()已废弃,如何修正对应add_filter代码消除错误?
Hey there, that deprecation warning is super common when working with older PHP code—let's get rid of it while keeping your functionality totally intact.
The Problem
create_function() got deprecated in PHP 7.2 for good reasons: it's prone to code injection risks (since it builds functions via string manipulation) and is far less flexible than modern PHP features. Your original code uses it to create a simple callback for the filter:
add_filter( 'option_page_capability_' . ot_options_id(), create_function( '$caps', "return '$caps';" ), 999 );
The Fix: Use an Anonymous Function (Closure)
PHP 5.3+ supports native anonymous functions (closures), which are the perfect drop-in replacement here. They're safer, cleaner, and won't trigger deprecation warnings. Here's your updated code:
add_filter( 'option_page_capability_' . ot_options_id(), function( $caps ) { return $caps; }, 999 );
What Changed?
- We swapped out the
create_function()call for a native anonymous function. The core logic stays identical: it accepts the$capsparameter and returns it right back, so your filter behaves exactly as it did before. - Unlike
create_function(), closures don't rely on string parsing—this eliminates injection risks and makes the code easier to read and modify later on.
If you ever need to reference external variables in the callback down the line, you can use the use() keyword to pull them into the closure's scope (here's a quick example):
$custom_cap = 'manage_options'; add_filter( 'option_page_capability_' . ot_options_id(), function( $caps ) use ( $custom_cap ) { return $custom_cap; }, 999 );
内容的提问来源于stack exchange,提问作者Денис Линник

