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){
...
...
}
}