Search code examples
phpninja-forms

Manipulate ninja forms mail body


How can I manipulate the ninja forms (3) mail body based on the input of the user?

example:

The user fills in the zipcode field and I wan't to add data to the mail body of the closest store.

The only useful filter I've found is "ninja_forms_submit_data". But it returns only field ID's and the user input.

What I need is a field key so I can use that as a reference.


Solution

  • There's a filter named ninja_forms_action_email_message that can be used to customise the email body. Source code is here.

    The filter has three arguments:

    1. $message This is a (HTML) string of the current email body
    2. $data Form data (includes data about the form and user submission)
    3. $action_settings Params for sending the email (to address, etc.)

    Example:

    function custom_email_body_content($message, $data, $action_settings) {
        // You may want to check if the form needs to be customised here
        // $data contains information about the form that was submitted
        // Eg. if ($data[form_id]) === ...
    
        // Convert the submitted form data to an associative array
        $form_data = array();
        foreach ($data['fields'] as $key => $field) {
            $form_data[$field['key']] = $field['value'];
        }
    
        // Do something to the email body using the value of $form_data['zipcode']
        // Maybe a str_replace of a token, or generate a new email body from a template
    
        // Return the modified HTML email body
        return $message;
    }
    
    add_filter('ninja_forms_action_email_message', 'custom_email_body_content', 10, 3);