Skip to content
Advertisement

#WordPress How to run contact form 7 filter inside a function [closed]

If i used the filter outside the function it works perfectly but i need to run the filter inside specific condition

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);
    }
}

Advertisement

Answer

You need to flip how you think about things a bit. Hooks (actions and filters) are called by plugins when the plugin wants to call them, not when you want them to be called. So you need to have the hook run always, and move the conditional logic of your function into the hook’s callback.

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
);
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement