I'm developing a plugin that creates a custom table upon plugin activation. The plugin allows users to add a form shortcode to collect data for leads.
I've got to the point where either the data saves but I can't create a new post (I'll get the "headers already sent" when the publish button is cliked in the WP editor) or, I'm able to create a new post, the form does display via shortcode BUT the data does not save to the database.
I've been pulling my hair out trying to figure out what I'm doing wrong.
Any help in the right direction would be much appreciated.
Here is the form process code.
//Process form data
function el_process_form(){
if (isset($_POST['everlead'])) {
if( $_SERVER['REQUEST_METHOD'] == 'POST' && !empty( $_POST['post_type'] ) && $_POST['post_type'] == "everlead"){
$name = stripcslashes($_POST["name"]);
$email = stripcslashes($_POST["email"]);
$phone = stripcslashes($_POST["phone"]);
$website = stripcslashes($_POST["website"]);
// Do some minor form validation to make sure there is content
if (trim($name) == "" ) {
echo 'Please enter your name. <br />';
}
if (trim($email) == "" ) {
echo 'Please enter a valid email address.<br/>';
}
if (trim($phone) == "" ) {
echo 'Please enter a contact number.<br/>';
}
if (trim($website) == "" ) {
echo 'Please enter your website url.<br/>';
}
global $wpdb;
//Set time
$formtime = date('m-d-Y h:i:a');
$ipaddress = $_SERVER['REMOTE_ADDR'];
//Table data
$data = array(
'name' => $name,
'email' => $email,
'phone' => $phone,
'website' => $website,
'date' => $formtime,
'ipaddress' => $ipaddress
);
//set lead data
$table = $wpdb->prefix . 'el_leads';
$wpdb->insert( $table, $data, array('%s', '%s', '%s', '%s', '%s') );
}
}
}
add_action( 'init', 'el_process_form' );
One weird thing with the code above ^^^. Everything works fine if on a local server (xampp) you remove if (isset($_POST['everlead'])) {
but I get the "headers already sent" error when on a live site.'
Also, If I add this if statement before the form process, I'm not able to save the data to the database.
function el_process_form(){
if(isset($_POST['post_type'])){
...process form data
}
}
add_action('init', 'el_process_form' );
The code above allows me to create a new post (as stated in previous paragraph) but the data does not save.
init
is the proper place to process the form. Much less doingecho
s. It could be inside the very shortcode, no?