0

I've a little PHP Script with a input Form which is used to register for a newsletter. This Form accepts only an email address and then makes an api call using curl.

Now I wan't to build this form as a plugin for wordpress. It should be easy usable on different pages with a shortcode. I have already build this plugin. I have a Form and I can display this form with the Shortcode. But I don't know how build the functions from my original php file in wordpress. I don't know how to send the form to itself and work with the values. Also I need to work with get parameters which are used to confirm a user.

Here is my original script, I think it's much easier to understand what I wan't to do:

index.php:

    <?php

    require_once('functions.php');

    // task subscribe

        if(isset($_POST['task'])){
            $task = $_POST['task'];
            if ($task == "subscribe"){
                if(!empty($_POST['email'])){
                    $email      = $_POST['email'];
                    $group      = basic;

                    $data = array(
                        "group"       => $group,
                        "email"       => $email
                    );
                    $response = doCurlRequest($task, $data);
                }
            }
        }

    // task = confirm

        if(isset($_GET['task']) && isset($_GET['hash'])){
            $task = $_GET['task'];
            $hash = $_GET['hash'];

            $data = array("hash" => $hash);  

            $response = doCurlRequest($task, $data);
        }

    // send mail with confirm link

        if(isset($response['subscriptions']['0'])){

            $to = $response['email'];
            $title = "confirm your address";
            $from = "From: Newslettersystem <newsletter@domain.tld>";
            $text = "
                Please confirm your address: http://domain.tld/index.php?task=confirm&hash=".$response['subscriptions']['0']['hash']."
            ";

            mail($to, $title, $text);

        }

?>

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
        <title>Newsletter Form Test</title>
    </head>
    <body>
        <h1>Newsletter Form</h1>
        <form method="post" action="<?php echo $_SERVER["PHP_SELF"]; ?>" name="newsletterForm">
            <input type="hidden" name="task" value="subscribe">
            <div>
                <label for="email">E-Mail Adresse *</label>
                <input type="text" name="email" id="email" size="30">
            </div>
            <div>
                <input type="submit" value="absenden">
            </div>
        </form>
    </body>
</html>

functions.php:

function doCurlRequest($task, $data){

    $data_string = json_encode($data);

    // Get cURL resources
    $curl = curl_init();

    // Set some options - we are passing in a useragent too here
    curl_setopt_array($curl, array(
        CURLOPT_RETURNTRANSFER => 1,
        CURLOPT_URL => 'http://domain.tld/api/emailing/v0.1/'.$task,
        CURLOPT_USERAGENT => 'Wordpress Form cURL Request',
        CURLOPT_POST => 1,
        CURLOPT_POSTFIELDS => $data_string,
        CURLOPT_HTTPHEADER => array('Content-Type: application/json', 'Content-Length:' . strlen($data_string))                                                                       
    ));

    // Send the request & save response to $resp
    $resp = json_decode(curl_exec($curl), true);

    // Close request to clear up some resources
    curl_close($curl);

    return $resp;

}

Okay, that's the original script which is working. And here is my starting point for wordpress:

<?php

/**
 * Plugin Name: NewsletterFormConnector
 * Description: Newsletter Form to connect to Newsletter Api
 * Author: emjay
 * Version: 1.0
 */

    function addCustomQueryVars( $vars ){
        $vars[] = "task";
        $vars[] = "hash";
        return $vars;
    }

    add_filter( 'query_vars', 'addCustomQueryVars' );

    function createForm(){

        $task = get_query_var( 'task' );
        $hash = get_query_var( 'hash' );

        $form  ="";

        $form .= '<form>';
        $form .= 'E-Mail: <input type="text" name="email">';
        $form .= '</form>';

        return $form;

    }

    add_shortcode('newsletterForm', 'createForm');

?>

I hope someone could give me some hints, how I can do this with a shortcode plugin. The shortcode should work on every page and the form is send to itself to make the api calls. But also I need that the page with a Form is responding to GET Parameters from the url so that a user can confirm it's address.

Thanks for your help,

emjay

1

First, create a function to process the form. In the shortcode function, first process the form and then return any form/message that you want to display to the user.

/**
 * Plugin Name: NewsletterFormConnector
 * Description: Newsletter Form to connect to Newsletter Api
 * Author: emjay
 * Version: 1.0
 */

//Add function file
require_once(plugin_dir_path(__FILE__) . 'functions.php');

//Add query var
function addCustomQueryVars( $vars ){
    $vars[] = "task";
    $vars[] = "hash";
    return $vars;
}

add_filter( 'query_vars', 'addCustomQueryVars' );

//Helper function to get current page url. You can put it in functions.php
//This is needed when sending message as the confirm page link needs to come to this page as well.
function current_page_url() {
    $pageURL = 'http';
    if( isset($_SERVER["HTTPS"]) ) {
        if ($_SERVER["HTTPS"] == "on") {$pageURL .= "s";}
    }
    $pageURL .= "://";
    if ($_SERVER["SERVER_PORT"] != "80") {
        $pageURL .= $_SERVER["SERVER_NAME"].":".$_SERVER["SERVER_PORT"].$_SERVER["REQUEST_URI"];
    } else {
        $pageURL .= $_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"];
    }
    return $pageURL;
}
//Shortcode function
function createForm(){
    //first process the form submit or confirm email task
    process();

    //All the task taken care of, now create html form and return it.

    $form  ="";

    $form .= '<form>';
    $form .= 'E-Mail: <input type="text" name="email">';
    $form .= '</form>';

    return $form;

}

add_shortcode('newsletterForm', 'createForm');

function process() {
    //Process post request
    if( isset($_POST['task']) ) {
        ....
        ....
        //I believe you can complete the process of send mail here
        if(isset($response['subscriptions']['0'])){
            ...
            ...
            $text = "
            Please confirm your address: " . current_page_url() . "?task=confirm&hash=".$response['subscriptions']['0']['hash']."
        ";
            //Send mail with wp_mail instead
            wp_mail($to, $title, $text, $from);
        }
        //Return to shortcode function
        return;
    }

    //Get query variables
    $task = get_query_var('task');
    $hash = get_query_var('hash');
    if( !empty($task) && !empty($hash){
        ...
        ...
    }
}
  • Hey :) Thanks for your great suggestions, I will try it out and come back to you later. Thanks! – emjay Aug 14 '14 at 9:42

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.