AJAX contact form for plugin via shortcode. WordPress OOP ex... open

AJAX contact form for plugin via shortcode. WordPress OOP example

Approved. Code works!
This is exactly the working code that is verified by the moderator or site administrators
Tested: PHP 5.6 +

A form of sending contact information that can be called anywhere using a shortcode. The form works on technology, and therefore sends data without reloading the page.

Let’s create our new class and name it class-contactform.php
We suggest you place the created file in the folder yourpluginname/inc/

File code:

<?php
class my_ContactForm {//create a new class

    public function __construct(){

        add_action('wp_enqueue_scripts',[$this,'enqueue']);//register our js script
        add_action('init',[$this,'contact_shortcode']); //register our shortcode 

        add_action('wp_ajax_contact_form',[$this,'contact_form']);//wp_ajax_contact_form - wp_ajax + contact_form (name of our processing function)
        add_action('wp_ajax_nopriv_contact_form',[$this,'contact_form']);//for unregistered users
    }

    public function enqueue(){ //connect our js script
        wp_enqueue_script('my_contactform', plugins_url('myplugin/assets/js/front/form.js'), array('jquery'),'1.0',true);//location of our file. Starting with the folder with all the plugins. myplugin eplace with the name of your plugin
   
        wp_localize_script('my_contactform','my_contactform_js',array( //function which will help to transfer terms in js
            'ajaxurl' => admin_url('admin-ajax.php'), //do not change
            'nonce' => wp_create_nonce('_wpnonce'),//security check
            'title' => esc_html__('Contact Form','myplugin'),//
        ));
    }

    public function contactform_shortcode(){ //create a shortcode for our form
        add_shortcode('contact_shortcode',[$this,'myform_html']);
    }

    public function myform_html($atts, $content){

        extract(shortcode_atts(array( //get the address of the page through our shortcode
            'url' => '',//default value
        ),$atts));

        //Let's create a html form
        echo '
        <div id="form_result"></div>
        <form method="post">
            <p>
                <input type="text" name="name" id="contactform_name"/> 
            </p>
            <p>
                <input type="text" name="email" id="contactform_email"/>
            </p>
            <p>
                <input type="text" name="phone" id="contactform_phone" />
            </p>';

            if($url != ''){
                echo '<p>
                    <input type="hidden" name="url" id="contactform_url" value="'.esc_html($url).'" />
                </p>';
            }

            echo '<p>
                <input type="submit" name="submit" id="contactform_submit" />
            </p>
            </form>';
    }

    function contact_form(){//function for processing results and sending a message to the administrator

        //check nonce
        check_ajax_referer('_wpnonce', 'nonce');//_wpnonce id from php, nonce - fromjs

        if(!empty($_POST)){

            if(isset($_POST['name'])){
                $name = sanitize_text_field($_POST['name']);
            }
            if(isset($_POST['email'])){
                $email = sanitize_text_field($_POST['email']);
            }
            if(isset($_POST['phone'])){
                $phone = sanitize_text_field($_POST['phone']);
            }
            //email Admin
            $data_message = '';

            $data_message .= 'Name: '.esc_html($name).'<br>';
            $data_message .= 'Email: '.esc_html($email).'<br>';
            $data_message .= 'Phone: '.esc_html($phone).'<br>';

            $result_admin = wp_mail(get_option('admin_email'), 'New appeal', $data_message);
            
            if($result_admin){//check whether the message was sent to the administrator
                 echo "Sended";
            } else {
                echo "Error!!!";
            }

            //email client
            $message = esc_html__('Thank you! We contat you soon!');//email text
            wp_mail($email, esc_html__('form submitted','myplugin'), $message);

        } else {
            echo 'Error';
        }

        wp_die();//wordpress analog function die()
    }
   
}

$contact_form = new my_ContactForm();

The code specifies the path to our js file located at myplugin/assets/js/front/form.js
Create this file and add the code below

jQuery(document).ready(function($){

    $('contactform_submit').on('click',function(e){//track the click on submit button of our form
        e.preventDefault();//cancel the standard action of the form
          
    });
        $.ajax({//create ajax
            url: my_contactform_js.ajaxurl,   //$(this).attr('href'),
            type: "POST",
            data: {
                
                action: "contact_form", //name handler function (created in our class on PHP)
                nonce: my_contactform_js.nonce,
                title: my_contactform_js.title,
                name:$('#contactform_name').val(),
                email:$('#contactform_email').val(),
                phone:$('#contactform_phone').val(),
                url:$('#contactform_url').val(),
            },
            success: function(data){
                $('#form_result').html(data);
            },
            error: function(errorThrown) {
                alert(errorThrown);
            }
    });
});

Now in the main file of your plugin yourpluginname.php attach your class-contactform.php file:

require plugin_dir_path(__FILE__) . 'inc/class-contactform.php';

On the page where our form will be called we will add:

$currenturl = get_permalink();

This will help us understand from which page the appeal came.

Now we are modifying our shortcode to pass the address of the page from which the request came

<?php echo do_shortcode('[contact_shortcode ulr="'.$currenturl.'"]'); ?>

You can use this code directly in your articles:

[contact_shortcode]

Stylize your contactform by adding basic CSS styles. Create and pass additional variables to the shortcode.
Good luck!

0

More

Leave a Reply

Your email address will not be published. Required fields are marked *

How many?: 22 + 22

lil-code© | 2022 - 2024
Go Top
Authorization
*
*
Registration
*
*
*
*
Password generation