php 基于多维数组动态执行几个remove_action()调用

xsuvu9jc  于 2023-04-19  发布在  PHP
关注(0)|答案(1)|浏览(93)

我尝试在我的WordPress应用程序中基于具有特定结构的配置数组动态执行一系列remove_action()函数调用。
硬编码,正确的执行将是:

remove_action('genesis_after_header', 'genesis_do_nav');
remove_action('genesis_after_header', 'genesis_do_subnav');
remove_action('genesis_site_title', 'genesis_seo_site_title', 5);

我想基于一个多维数组执行相同的执行,如下所示:

$config = array(
    'remove_actions' => [
        'genesis_after_header' => [
            'genesis_do_nav',
            'genesis_do_subnav'
        ],
        'genesis_site_title' => [
            'genesis_seo_site_title' => 5
        ],
    ],
);

下面是我尝试迭代配置数组来执行三个remove_action()调用:

foreach ($config as $hook => $functions) {
    foreach ($functions as $function => $priority) {
        if (! is_null($priority)) {
            remove_action($hook, $function);
        } else {
            remove_action($hook, $function, $priority);
        }
    }
}

这不能按预期正确访问值。

6ie5vjzr

6ie5vjzr1#

调整配置结构,使$function始终来自一个键,其值(可能是null)将是$priority

$config = [
    'remove_actions' => [
        'genesis_after_header' => [
            'genesis_do_nav' => null,
            'genesis_do_subnav' => null,
        ],
        'genesis_site_title' => [
            'genesis_seo_site_title' => 5
        ],
    ],
];

访问数据时,第一个循环必须访问$config['remove_actions'] . Demo

foreach ($config['remove_actions'] as $hook => $functions) {
    foreach ($functions as $function => $priority) {
        if (is_null($priority)) {
            remove_action($hook, $function);
        } else {
            remove_action($hook, $function, $priority);
        }
    }
}

相关问题