我在函数中有一些代码。我可以轻松地用更短的函数替换php,例如:
function register_sections() {
add_settings_section(\'SOMETHING_settings\', \'SOMETHING Settings\', \'generate\', \'SOMETHING_page\' );
add_settings_section(\'SOMETHING2_settings\', \'SOMETHING2 Settings\', \'generate\', \'SOMETHING2_page\' );
add_settings_section(\'SOMETHING3_settings\', \'SOMETHING3 Settings\', \'generate\', \'SOMETHING3_page\' );
add_settings_section(\'SOMETHING4_settings\', \'SOMETHING4 Settings\', \'generate\', \'SOMETHING4_page\' );
(...)
}
add_action(\'admin_init\', \'register_sections\');
我猜替换上述代码的函数如下所示:
function settings_sections() {
$array = (\'SOMETHING\',\'SOMETHING2\',\'SOMETHING3\', \'SOMETHING4\');
foreach($array as $section) {
echo "add_settings_section(\'".$section."_settings\',\'".$section." Settings\',\'generate\',\'".$section."_page\' ) ;";
}
但我不知道如何初始化这个动态生成的内容?当然
add_action(\'admin_init\', \'settings_sections\');
在所有管理页面上回显函数的输出,而不是注册节。
最合适的回答,由SO网友:mor7ifer 整理而成
请尝试以下操作:
function settings_sections() {
// array containing settings identifiers
$array = ( \'SOMETHING\', \'SOMETHING2\', \'SOMETHING3\', \'SOMETHING4\' );
// loop through settings identifiers and generate settings sections
foreach( $array as $v) {
add_settings_section(
$v . \'_settings\',
$v . \' Settings\',
\'generate\',
$v . \'_page\'
);
}
}
echo
输出字符串,您应该只调用
add_settings_section()
直接从回路内部。
此外,注意:generate()
不是函数的最佳名称,您应该使用一些不太可能与另一个函数重叠的名称(在其前面加上前缀)