Сustomizing the email message generated by Form Smart Action

Hello.

My question is related to the section of the documentation about using a Form Action. In the section CUSTOMIZING THE EMAIL MESSAGE it is written:

Use the WordPress filter pg_form_email to customize the email message and title. Inspect the inc/wp_pg_helpers.php to see how it works and what kind of data it gets.

However, there is no mention of working with the pg_form_email filter in the code of the wp_pg_helpers.php file. I was expecting to see something like:

$output = apply_filters ('pg_form_email', $unmodified_output, ..., ...);

Because of what this code does not work for me (in inc/custom.php):

add_filter( 'pg_form_email', 'modify_email_message' );

function modify_email_message( $email_massage ) {
    // modifying the $email_massage
    return $email_massage;
}

The question is: how to properly modify the text of an email message? And additionally: how to modify the content of a custom post by analogy (where the data from the form is also saved), if I selected the Register custom post type item in the Smart Form Action settings? For example, I want to change the standard name attributes of the form fields:

with prettier words:

Content of my inc/wp_pg_helpers.php file:

<?php
/**
 * Class Name: PG_Image, PG_Helper
 * GitHub URI:
 * Description:
 * Version: 1.0
 * Author: Matjaz Trontelj - @pinegrow
 * License: GPL-2.0+
 * License URI: http://www.gnu.org/licenses/gpl-2.0.txt
 *
 */

class PG_Image {

    static function removeSizeAttributes( $img, $attr = null ) {
        if( $attr == 'both' || $attr == 'width') {
            $img = preg_replace('/\swidth="[^"]*"/i', '', $img);
        }
        if( $attr == 'both' || $attr == 'height') {
            $img = preg_replace('/\sheight="[^"]*"/i', '', $img);
        }
        return $img;
    }

    static function getUrl( $image_or_url, $size ) {
        if(!is_numeric( $image_or_url )) {
            return $image_or_url;
        }
        return wp_get_attachment_image_url( $image_or_url, $size );
    }

    static function getImages( $list ) {
        if(empty( $list )) return array();
        if(is_string( $list )) $list = explode( ',', $list );
        $args = array(
            'post__in'       => $list,
            'post_type'      => 'attachment',
            'post_mime_type' => 'image',
            'posts_per_page' => -1,
            'orderby'        => 'post__in',
            'order'          => 'ASC'
        );
        return get_posts( $args );
    }

    static function isPostImage() {
        global $post;
        return $post->post_type === 'attachment' && !empty( $post->post_mime_type ) &&  strpos( $post->post_mime_type, 'image' ) === 0;
    }

    static function getPostImage( $id, $size, $args, $remove_sizes = null, $default_img = null) {
        $img = '';

        if(empty($id) && self::isPostImage()) {
            $img = wp_get_attachment_image( get_the_ID(), $size, false, $args);

        } else if(has_post_thumbnail($id)) {
            $img = get_the_post_thumbnail( $id, $size, $args);
        }

        if(!empty($default_image) && empty($img)) {
            $img = $default_img;
        }

        if(!empty($img) && !empty($remove_sizes)) {
            $img = self::removeSizeAttributes( $img, $remove_sizes );
        }
        return $img;
    }
}

class PG_Helper {

    static function getPostFromSlug( $slug_or_id, $post_type ) {
        if( is_numeric( $slug_or_id ) ) {
            return $slug_or_id;
        }
        return get_page_by_path( $slug_or_id, OBJECT, $post_type );
    }

    static function getTermFromSlug( $slug_or_id, $taxonomy ) {
        if( is_numeric( $slug_or_id ) ) {
            return $slug_or_id;
        }
        switch( $taxonomy ) {
            case 'category':
                return get_category_by_slug( $slug_or_id );
            default:
                return get_term_by( 'slug', $slug_or_id, $taxonomy );
        }
    }

    static function addAttributesToElements( $tag, $attrs, $html ) {
        $attr_str = '';

        foreach( $attrs as $name => $val ) {
            $attr_str .= " {$name}";
            if(!is_null($val)) {
                $attr_str .= "=\"{$val}\"";
            }
        }

        if(!empty($attr_str)) {
            $html = str_replace("<{$tag} ", "<{$tag}{$attr_str} ", $html);
            $html = str_replace("<{$tag}>", "<{$tag}{$attr_str}>", $html);
        }

        return $html;
    }

    static $shown_posts = array();

    static function rememberShownPost( $p = null ) {
        global $post;
        if(empty( $p )) {
            $p = $post;
        }
        if(!empty($p) && !in_array( $p->ID, self::$shown_posts)) {
            self::$shown_posts[] = $p->ID;
        }
    }

    static function getShownPosts() {
        return self::$shown_posts;
    }

    static function getInsightMetaFields() {
        $list = array();
        $meta = get_post_meta( get_the_ID() );
        if($meta) {
            foreach($meta as $key => $values) {
                if(strpos($key, '_') !== 0) {
                    $list[] = $key;
                }
            }
        }
        echo '<!-- PG_FIELDS:'.implode(',', $list).'-->';
    }

    static function getRelationshipFieldValue( $field ) {
        if( function_exists( 'get_field' )) {
            return get_field( $field, false, false );
        } else {
            $value = get_post_meta( get_the_ID(), $field );
            if( empty( $value ) ) {
                return null;
            }
            if(count($value) === 1) {
                if(strpos($value[0], 'a:') >= 0 && strpos($value[0], '{') >= 0) {
                    return unserialize($value[0]);
                }
                if(is_string($value[0])) {
                    return explode(',', $value[0]);
                }
            }
            return $value;
        }
    }

    static function getPostIdList( $value ) {
        if( empty( $value )) {
            return array(-1);
        }
        if(is_string($value)) {
            $value = explode(',', $value);
        }
        if(is_numeric($value)) {
            $value = array($value);
        }
        if(is_array($value) && count($value) === 0) {
            $value = array(-1);
        }
        return $value;
    }

    static function getBreadcrumbs( $type = 'parents', $add_home = false, $home_label = '' ) {
        global $post;

        $r = array();

        if($type === 'parents') {
            $parents = get_post_ancestors( $post->ID );
            foreach($parents as $parent_id) {
                $p = get_post( $parent_id );
                $r[] = array(
                    'name' => get_the_title( $p ),
                    'link' => get_permalink( $p )
                );
            }
        } else {
            $category = get_the_category( $post->ID );

            if(!empty($category)) {
                $parents = get_ancestors($category[0]->term_id, 'category');

                array_unshift( $parents, $category[0]->term_id );

                foreach ($parents as $parent_id) {
                    $p = get_category($parent_id);
                    $r[] = array(
                        'name' => $p->name,
                        'link' => get_category_link($p)
                    );
                }
            }
        }

        array_unshift($r, array(
            'name' => get_the_title( $post ),
            'link' => get_permalink( $post )
        ));

        if($add_home) {
            $r[] = array(
                'name' => $home_label,
                'link' => home_url()
            );
        }

        return array_reverse( $r );
    }
}

Hi @Catative,
Sorry, we changed this feature up a bit a few versions ago and missed the documentation update. Pinegrow now makes a separate file called wp_simple_form_mailer.php within the export inc file.

For email, the portion you are interested in is:

if($options['send_to_email']) {
$headers = 'From: '. $admin_email . "\r\n";

$email_data = array(
'headers' => $headers,
'subject' => $options['title'],
'content' => $text,
'data' => $form_data
);

$email_data = apply_filters( 'pg_form_email', $email_data);

$emailed = wp_mail($options['email'], $email_data['subject'], $email_data['content'], $email_data['headers']);
}

You can see the apply_filters to be called with the add_filteras you are doing above. You then want to change the value of $email_data[‘content’] using the submitted data in $email_data[‘data’], and pass the array back. I hope this makes sense.

For the post, there are much more limited options for changing the format, but changing the name attributes in the postust requires changing the name attribute for the field. You can use the numeric entity reference for the space &#160. So the first input field would have an attribute of name="Client&#160name". For the apostrophe use &#39

Hope this helps,
Bob

Thank you so much for the comprehensive information, @RobM!

With the help of my IDE (PhpStorm) I searched the whole project for the string 'pg_form_email', but found nothing. Also, the wp_simple_form_mailer.php file does not contain the program code that you wrote in your previous post. Most likely, you haven’t migrated the updated code from Pinegrow Pro WordPress builder to Pinegrow Theme Converter yet.

I am currently using Pinegrow Theme Converter v1.3 on Linux Kubuntu 20.04 operating system.

The content of my wp_simple_form_mailer.php file is as follows:

<?php
/**
 * Class Name: PG_Simple_Form_Mailer
 * GitHub URI:
 * Description:
 * Version: 1.0
 * Author: Matjaz Trontelj - @pinegrow
 * License: GPL-2.0+
 * License URI: http://www.gnu.org/licenses/gpl-2.0.txt
 *
 */


class PG_Simple_Form_Mailer {

    public $processed = false;
    public $error = true;
    public $message = 'The form was not submitted';
    public $text = null;
    public $html = null;

    public function process( $arg_options = array() ) {

        $admin_email = get_option('admin_email');

        $options = array(
            'form_id' => 'contact_form',
            'send_to_email' => false,
            'email' => $admin_email,
            'title' => 'Contact form submission',
            'intro' => 'We received a new contact form submission:',
            'save_to_post_type' => null,
            'post_type' => null,
            'captcha' => false,
            'captcha_key' => null,
            'captcha_secret' => null,
            'log_ip' => true,
            'success_message' => 'Thank you for getting in touch!',
            'error_message' => 'There was a problem submitting this form. Please contact us directly.'
        );

        //merge options
        foreach($arg_options as $key => $value) {
            $options[ $key ] = $value;
        }

        if( !empty($_POST[$options['form_id']]) ) {
            //the form was submitted
            //we assume the browser did the validation
            $lf = "\n\r";

            $ignore_fields = array($options['form_id'], 'g-recaptcha-response');

            $text = $options['intro'].$lf.$lf;
            $html = "<p>{$options['intro']}</p>";

            $from_email = null;

            $this->processed = true;

            if($options['captcha']) {
                if(empty($options['captcha_key']) || empty($options['captcha_secret'])) {
                    $this->error = 'Captcha key and secret are not set.';
                    return true;
                }

                if(empty($_POST['g-recaptcha-response'])) {
                    $this->error = 'Captcha response is not present.';
                    return true;

                } else if($this->validate_rechapcha($_POST['g-recaptcha-response'], $options['captcha_secret']) !== true) {
                    $this->error = 'Captcha validation failed.';
                    return true;
                }
            }

            foreach($_POST as $key => $value) {
                if(!in_array( $key, $ignore_fields)) {
                    $key = filter_var($key, FILTER_SANITIZE_STRING);
                    $value = filter_var($value, FILTER_SANITIZE_STRING);

                    $text .= "{$key}: {$value}".$lf;

                    if($key == 'email' || $key == 'Email') {
                        $from_email = $value;
                    }

                    $html .= "<p><b>{$key}</b>: {$value}</p>";
                }
            }

            $stamp = "Submitted on ".date("F j, Y, g:i a");
            if($options['log_ip'] && !empty($_SERVER['REMOTE_ADDR'])) {
                $stamp .= " from ".$_SERVER['REMOTE_ADDR'];
            }

            $text .= $stamp;
            $html .= "<p><em>{$stamp}</em></p>";

            $this->text = $text;
            $this->html = $html;

            $emailed = null;
            $saved = null;

            if($options['send_to_email']) {
                $headers = 'From: '. $admin_email . "\r\n";
                $emailed = wp_mail($options['email'], $options['title'], $text, $headers);
            }
            if($options['save_to_post_type']) {
                if(wp_insert_post( array(
                    'post_title' => $options['title'].(!empty( $from_email ) ? (" - ".$from_email) : ""),
                    'post_content' => $html,
                    'post_type' => $options['post_type'],
                    'post_status' => 'private'
                ) )) {
                    $saved = true;
                } else {
                    $saved = false;
                }
            }

            if((!$emailed && !$saved) || $emailed === false || $saved === false) {
                $this->error = true;
                $this->message = $options['error_message'];
            } else {
                $this->error = false;
                $this->message = $options['success_message'];
            }

            return true;
        } else {
            //the form was not submitted
            $this->processed = false;
            $this->error = false;
            return false;
        }

    }

    //source https://gist.github.com/jonathanstark/dfb30bdfb522318fc819
    public function validate_rechapcha($response, $secret)
    {
        // Verifying the user's response (https://developers.google.com/recaptcha/docs/verify)
        $verifyURL = 'https://www.google.com/recaptcha/api/siteverify';

        $query_data = [
            'secret' => $secret,
            'response' => $response,
            'remoteip' => (isset($_SERVER["HTTP_CF_CONNECTING_IP"]) ? $_SERVER["HTTP_CF_CONNECTING_IP"] : $_SERVER['REMOTE_ADDR'])
        ];

        // Collect and build POST data
        $post_data = http_build_query($query_data, '', '&');

        // Send data on the best possible way
        if (function_exists('curl_init') && function_exists('curl_setopt') && function_exists('curl_exec'))
        {
            // Use cURL to get data 10x faster than using file_get_contents or other methods
            $ch = curl_init($verifyURL);
            curl_setopt($ch, CURLOPT_POST, 1);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
            curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
            curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
            curl_setopt($ch, CURLOPT_TIMEOUT, 5);
            curl_setopt($ch, CURLOPT_HTTPHEADER, array('Accept: application/json', 'Content-type: application/x-www-form-urlencoded'));
            $response = curl_exec($ch);
            curl_close($ch);
        }
        else
        {
            // If server not have active cURL module, use file_get_contents
            $opts = array('http' =>
                array(
                    'method' => 'POST',
                    'header' => 'Content-type: application/x-www-form-urlencoded',
                    'content' => $post_data
                )
            );
            $context = stream_context_create($opts);
            $response = file_get_contents($verifyURL, false, $context);
        }

        // Verify all reponses and avoid PHP errors
        if ($response)
        {
            $result = json_decode($response);
            if ($result->success === true)
            {
                return true;
            }
            else
            {
                return $result;
            }
        }

        // Dead end
        return false;
    }

}

Hi @Catative,
My apologies. You are correct. That file hasn’t been updated, but I also see that when it was updated we didn’t change the version number. At any point, I’m really sorry. It seems that the filter is only active in the Pinegrow Pro Wordpress Builder. I’m not sure when the next update for the Theme Converter will be.
Sorry for the inconvenience,
Bob

1 Like