#WordPress 如何 运行 在函数内联系表单 7 过滤器

#Wordpress How to run contact form 7 filter inside a function

如果我在函数外部使用过滤器,它可以完美运行,但我需要运行特定条件下的过滤器

function run_filter()
{
    $url = home_url(add_query_arg(NULL, NULL));
    if (!(strpos($url, 'id') && strpos($url, 'form_id'))) {
        add_filter('wpcf7_validate_tel*', 'number_field_exist', 10, 2);
    }
}

你需要稍微改变一下你对事情的看法。挂钩(动作和过滤器)在插件想要调用它们时由插件调用,而不是在您希望它们被调用时调用。因此,您需要始终拥有钩子 运行,并将函数的条件逻辑移动到钩子的回调中。

add_filter(
    'wpcf7_validate_tel*',
    static function ($result, $tag) {

        // Conditional logic that used to be in the function
        $url = home_url(add_query_arg(null, null));
        if (!(strpos($url, 'id') && strpos($url, 'form_id'))) {

            // This is the original callback, now moved here.
            // Assign the result back to the filter's first argument
            $result = number_field_exist($result, $tag);
        }

        // No matter what, we need to return something because this is a filter
        return $result;
    },
    'number_field_exist',
    10,
    2
);