So I am almost done creating this anti spam google recaptcha v3 form.
I get failure to the end.
could you see what is the problem?
I dont use this to send data to DB but to my email.
let me know if this is the problem, but i think not.
I am almost finished, here what I have done so far:
(still getting Failed to save data. error)
<?php
if(isset($_POST['submit'])){
// print_r($_POST);
$url = "https://www.google.com/recaptcha/api/siteverify";
$data = [
'secret' => "censord",
'response' => $_POST['token'],
'remoteip' => $_SERVER['REMOTE_ADDR']
];
$options = array(
'http' => array(
'header' => "Content-type: application/
x-www-form-urlencoded\r\n",
'method' => 'POST',
'content' => http_build_query($data)
)
);
$context = stream_context_create($options);
$response = file_get_contents($url, false, $context);
$res = json_decode($response, true);
if($res['success'] == true) {
//save data to database
echo '<div class="alert alert-success">
<strong>Success!</strong> Data is saved.
</div>';
} else {
echo '<div class="alert alert-warning">
<strong>warning!</strong> Failed to save data.
</div>';
}
}
?>
------------------- and the form-----------
<?php
if(isset($_POST['submit'])){
$name = htmlspecialchars(stripslashes(trim($_POST['username'])));
$email = htmlspecialchars(stripslashes(trim($_POST['email'])));
$text = htmlspecialchars(stripslashes(trim($_POST['textt'])));
if(!preg_match("/^[A-Za-z .'-]+$/", $name)){
$name_error = 'Invalid name';
}
if(!preg_match("/^[A-Za-z0-9._%+-]+#[A-Za-z0-9.-]+\.[A-Za-z]{2,4}$/", $email)){
$email_error = 'Invalid email';
}
if(strlen($text) === 0){
$message_error = 'Your message should not be empty';
}
if(preg_match('/http|www/i',$comments)) {
$error_message .= "We do not allow a url in the comment.<br />";
}
}
?>
<div id="container">
<div class="form-wrap">
<h1>Report bug</h1>
<p>It's free and you help us make the programming wikipedia better!</p>
<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" method="POST">
<div class="form-group">
<label for="username">Name:</label>
<input type="text" name="username">
<p><?php if(isset($name_error)) echo $name_error; ?></p>
</div>
<div class="form-group">
<label for="email">Email:</label>
<input type="email" name="email">
<p><?php if(isset($email_error)) echo $email_error; ?></p>
</div>
<div class="form-group">
<label for="textx">Message:</label>
<textarea type="text" name="textt" rows="22" cols="42"></textarea>
<p><?php if(isset($message_error)) echo $message_error; ?></p>
<button type="submit" name="submit" value="Submit" class="btn">Report us</button>
<?php
if(isset($_POST['submit']) && !isset($name_error) && !isset($subject_error) && !isset($email_error) && !isset($message_error)){
$to = 'censord'; // edit here
$body = " Name: $name\n E-mail: $email\n Message:\n $message";
if(mail($to, $subject, $body)){
echo '<p style="color: green">Message sent</p>';
}else{
echo '<p>Error occurred, please try again later</p>';
}
}
?>
<input type="hidden" id="token" name="token">
</form>
</div>
</div>
</body>
<script>
grecaptcha.ready(function() {
grecaptcha.execute('censord', {action: 'homepage'}).then(function(token) {
console.log(token);
document.getElementById("token").value = token;
});
});
</script>
</html>
Related
I have an AJAX HTML form with validation fields. So my problem is that i'm stuck. I want to embed a recaptcha in my form. I want to produce the following result. If the user completes the recaptcha then the form will be sended. Now if i complete the form and the recaptcha correctly the form is not sended.
HTML
function sendContact() {
var valid;
valid = validateContact();
if(valid) {
jQuery.ajax({
url: "contact_mail.php",
data:'userName='+$("#userName").val()+'&userEmail='+$("#userEmail").val()+'&subject='+$("#subject").val()+'&content='+$(content).val(),
type: "POST",
success:function(data){
$("#mail-status").html(data);
},
error:function (){}
});
}
}
function validateContact() {
var valid = true;
$(".demoInputBox").css('background-color','');
$(".info").html('');
if(!$("#userName").val()) {
$("#userName-info").html("<span style='color: #F00423';>Απαιτούμενο πεδίο</span>");
$("#userName").css('background-color','#3E3E3E');
valid = false;
}
if(!$("#userEmail").val()) {
$("#userEmail-info").html("<span style='color: #F00423';>Απαιτούμενο πεδίο</span>");
$("#userEmail").css('background-color','#3E3E3E');
valid = false;
}
if(!$("#userEmail").val().match(/^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/)) {
$("#userEmail-info").html("<span style='color: #F00423';>Απαιτούμενο πεδίο</span>");
$("#userEmail").css('background-color','#3E3E3E');
valid = false;
}
if(!$("#subject").val()) {
$("#subject-info").html("<span style='color: #F00423';>Απαιτούμενο πεδίο</span>");
$("#subject").css('background-color','#3E3E3E');
valid = false;
}
if(!$("#content").val()) {
$("#content-info").html("<span style='color: #F00423';>Απαιτούμενο πεδίο</span>");
$("#content").css('background-color','#3E3E3E');
valid = false;
}
return valid;
}
</script>
<div id="frmContact">
<div id="mail-status"></div>
<div>
<span id="userName-info" class="info"></span><br/>
<input type="text" name="userName" id="userName" class="form-control form-dark demoInputBox" placeholder="Όνομα">
</div>
<div>
<span id="userEmail-info" class="info"></span><br/>
<input type="text" name="userEmail" id="userEmail" class="form-control form-dark demoInputBox" placeholder="Email">
</div>
<div>
<span id="subject-info" class="info"></span><br/>
<input type="number" name="subject" id="subject" class="form-control form-dark demoInputBox" placeholder="Τηλέφωνο">
</div>
<div>
<span id="content-info" class="info"></span><br/>
<textarea name="content" id="content" class="form-control form-dark demoInputBox" cols="60" rows="6" placeholder="Μήνυμα"></textarea>
</div>
<div>
<div class="g-recaptcha" data-theme="dark" data-sitekey="6LcoXZ0UAAAAAMdgKIlchJvizDWic5S7nwr5XD3g"></div>
<button name="submit" class="btn btn-border border-white btnAction" onClick="sendContact();">Αποστολη</button>
</div>
</div>
PHP
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// access
$secretKey = '6LcoXZ0UAAAAAF3U4SSfiKPZ7NWyuATN7NFh8fKE';
$captcha = $_POST['g-recaptcha-response'];
if(!$captcha){
echo '<p class="alert alert-warning">Please check the the captcha form.</p>';
exit;
}
$ip = $_SERVER['REMOTE_ADDR'];
$response=file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=".$secretKey."&response=".$captcha."&remoteip=".$ip);
$responseKeys = json_decode($response,true);
if(intval($responseKeys["success"]) !== 1) {
echo '<p class="alert alert-warning">Please check the the captcha form.</p>';
} else {
$to = "vp#digital-media.gr";
$msg = "name:\t$_REQUEST[userName]\n";
$msg .= "email:\t$_REQUEST[userEmail]\n";
$msg .= "tel:\t$_REQUEST[subject]\n";
$msg .= "message:\t$_REQUEST[content]\n";
$success = mail($to, "Mail from our site", $msg, "Content-type: text/plain; charset=UTF-8");
if($success) {
print "<p class='success'>Ευχαριστούμε, το μήνυμα σας έχει σταλθεί. Θα σας απαντήσουμε το συντομότερο.</p>";
} else {
print "<p class='Error'>Υπήρξε ένα σφάλμα, δοκιμάστε αργότερα! </p>";
}
}
?>
I have a 1 page website that is using scrollify.js.
I have 2 buttons to scroll the window to the relevant section for filling out the form and returning to the top of the page.
The first button is (icon2) with an (a) tag with a class of scrollToB.
The 2nd button (home-btn) with another (a) tag and a class of scrollTo that fades in and out so you can return to the top section on clicking this button.
Both functions to scroll and fade in and out are working until i click submit on the form and although the fade function still works on the button the seperate click functions on the 2 buttons (scrollify.move) have stopped working? This behaviour is the same whether the form fails validation or is sent?
a working example is www.devonfoodmovement.com
I have searched for hours and cant find anything relevant?
All scripts/styles are being loaded from my functions.php file
Index (front-page.php)
<?php get_header(); ?>
<article id="section_1">
<section class='section-class' data-section-name="devonfoodmovement">
<?php include('home-layout.php');?>
</section>
</article>
<article id="section_2">
<section class='section-class' data-section-name="contact us">
<?php include('form.php');?>
</section>
<div class="home-btn"><i class="fas fa-home"></i></div>
</article>
<?php get_footer(); ?>
</body>
</html>
home-layout.php
<?php ?>
<div class="container">
<div class="logo">
<div class="logo-image">
</div>
</div>
<div class="text">
<h1>Devon Food Movement</h1>
<h2>Website under construction <br class="textbreak">follow us below on ...</h2>
</div>
<div class="icons">
<div class="icon1"></div>
<div class="icon2"></div>
<div class="icon3"></div>
<div class="icon3m"></div>
</div>
</div>
functions.php
<?php
function register_my_menus() {
register_nav_menus(
array( 'header_menu' => __( 'Header Menu', 'DevonFoodMovement'),
'footer_menu' => __( 'Footer Menu', 'DevonFoodMovement')
)
);
}
add_action('init', 'register_my_menus');
/* GOOGLE FONTS */
function DFM_styles()
{
wp_register_style('DFM', get_template_directory_uri() . '/style.css', array(), '1.0', 'all');
wp_enqueue_style('DFM');
}
add_action('wp_enqueue_scripts', 'DFM_styles');
function DFM_form()
{
wp_register_style('DFMform-css', get_template_directory_uri() . '/form.css', array(), '1.0', 'all');
wp_enqueue_style('DFMform-css');
}
add_action('wp_enqueue_scripts', 'DFM_form');
function DFM_scripts()
{
wp_register_script('j-query-min', 'http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js' );
wp_enqueue_script('j-query-min');
wp_register_script('j-query-mob-min', 'http://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.js' );
wp_enqueue_script('j-query-mob-min');
wp_register_script( 'modernizr', get_template_directory_uri() . '/modernizr-1.6.min.js' );
wp_enqueue_script( 'modernizr' );
wp_register_script('scrollify-min', 'https://cdn.jsdelivr.net/npm/jquery-scrollify#1.0.17/jquery.scrollify.min.js' );
wp_enqueue_script('scrollify-min');
wp_register_script('jquery-custom', get_template_directory_uri() . '/customjs.js' );
wp_enqueue_script('jquery-custom');
}
add_action('wp_enqueue_scripts', 'DFM_scripts');
function load_fonts()
{
wp_register_style('et-googleFonts', 'https://fonts.googleapis.com/css?family=Josefin+Sans:300,400');
wp_enqueue_style( 'et-googleFonts');
}
add_action('wp_print_styles', 'load_fonts');
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
custom.js file
$(document).ready(function(){
$('article').css({'height':($(window).height())+'px'}).css({'width':($(window).width())+'px'});
$(window).resize(function(){
$('article').css({'height':($(window).height())+'px'}).css({'width':($(window).width())+'px'});
});
});
$(document).scroll(function(){
$(function() {
$.scrollify({
section: ".section-class",
sectionName : "section-name",
/*interstitialSection : ".footer-end",*/
scrollSpeed: 1000,
setHeights: true
});
});
});
$(document).scroll(function (){
if(window.location.href === "http://devonfoodmovement.com/#devonfoodmovement"){
$('.home-btn').fadeOut(500);
} else if(window.location.href === "http://devonfoodmovement.com/#contact-us") {
$('.home-btn').fadeIn(500).css('display','block');
}
});
$(document).ready(function (){
$(".scrollTo").click(function() {
$.scrollify.move(0);
});
});
$(document).ready(function (){
$(".scrollToB").click(function() {
$.scrollify.move(1);
});
});
form.php
<?php include ('form_process.php');?>
<div class="grey">
<div class="container-contact">
<form id="contact" method="post" >
<div id="column-contact-left">
<div class='contact-logo'></div>
<h3>Contact the Devon Food Movement</h3>
<fieldset id="field-no-ui">
<input placeholder="Your name" type="text" tabindex="1" name="name1" value="<?= $name ?>" >
</fieldset>
<span class="error"><?= $name_error ?></span>
<fieldset id="field-no-ui">
<input placeholder="Your Email Address" type="text" name="email" value="<?= $email ?>" tabindex="2" >
</fieldset>
<span class="error"><?= $email_error ?></span>
</div>
<div id="column-contact-right">
<fieldset id="field-no-ui">
<textarea id="field-no-ui" placeholder="Type your Message Here...." name="message" value="<?= $message ?>" tabindex="3" ></textarea>
</fieldset>
<div class="g-recaptcha" data-sitekey="sitekey" ></div>
<span class="captcha-failed"><?= $captchafailed; ?></span>
<span class="sent"><?= $sent; ?></span>
<fieldset id="field-no-ui">
<button name="submit" type="submit" id="contact-submit" data-submit="...Sending">Submit</button>
</fieldset>
</div>
</form>
<script src="https://www.google.com/recaptcha/api.js" async defer></script>
</div>
</div>
form-process.php
<?php
function post_captcha($user_response) {
$fields_string = '';
$fields = array(
'secret' => 'secret',
'response' => $user_response
);
foreach($fields as $key=>$value)
$fields_string .= $key . '=' . $value . '&';
$fields_string = rtrim($fields_string, '&');
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://www.google.com/recaptcha/api/siteverify');
curl_setopt($ch, CURLOPT_POST, count($fields));
curl_setopt($ch, CURLOPT_POSTFIELDS, $fields_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, True);
$result = curl_exec($ch);
curl_close($ch);
return json_decode($result, true);
}
$res = post_captcha($_POST['g-recaptcha-response']);
$name_error = $email_error = $captchafailed = "";
$name = $email = $message = $sent = "";
if (isset($_POST['submit']) AND (!$res['success'])) {
$captchafailed = "please check reCaptcha";
}
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["name1"])) {
$name_error = "Name is required";
} else {
$name = test_input($_POST["name1"]);
if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
$name_error = "Only letters and white space allowed";
}
}
if (empty($_POST["email"])) {
$email_error = "Email is required";
} else {
$email = test_input($_POST["email"]);
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$email_error = "Invalid email format";
}
}
if (empty($_POST["message"])) {
$message = "";
} else {
$message = test_input($_POST["message"]);
}
if ($name_error == '' and $email_error == '' and ($res['success']) ){
$message_body = '';
unset($_POST['submit']);
foreach ($_POST as $key => $value){
$message_body .= "$key: $value\n";
}
$email = $_POST['email'];
$to = '#gmail.com';
$subject = 'Contact Form Submit';
$headers = 'From:' . $email . "\n" . 'Reply-to: ' . $email . "\n" ;
if (mail($to, $subject, $message, $headers)) {
$sent = "Message sent";
$name = $email = $message = '';
}
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
I'm seeing a lot of issue here with the way this is put together.
First thing you can start with is to prevent the default behaviour of your move links.
$(".scrollTo").click(function(event) {
event.preventDefault();
$.scrollify.move(0);
});
Is there a way i can verify if my php script for sending form to emails worked? I tried running the php website in localhost and tested to submit a message but when I checked my email, nothing has been sent. How do I kno if my form has been received? Is it instantly received when you sent a message from php form via email? How do I know if the email script was wrong or it just didnt send? heres my html:
<div class="container">
<div class="row">
<div class="inquiry2 col-xs-12 col-sm-12 col-md-12 col-lg-12">
<br></br>
<br></br>
<h1>Message Us</h1>
<form action="send.php" id="frmBox" method="post" onsubmit="return formSubmit();">
<div class="form-group">
<label for="InputName">Name*</label>
<input class="form-control" type="text" placeholder="Name" name="customer_name" id="CustomerName">
</div>
<div class="form-group">
<label for="InputEmail">Email Address*</label>
<input class="form-control" type="text" placeholder="email" name="customer_email" id="CustomerEmail">
</div>
<div class="form-group">
<label for="InputPhone">Phone*</label>
<input class="form-control" type="text" placeholder="phone" name="customer_phone" id="CustomerPhone">
</div>
<div class="form-group">
<label for="InputMessage">Message*</label>
<textarea class="form-control" type="text" placeholder="" name="customer_message" id="CustomerMessage"></textarea>
</div>
<input class="btn btn-default" type="submit" value="submit">
</form>
</div>
</div>
</div>
<!--SCRIPT-->
<script type="text/javascript" src="js/jquery-3.2.1.min.js"></script>
<script type="text/javascript">
function formSubmit(){
$.ajax({
type:'POST',
url:'send.php',
data:$('#frmBox').serialize(),
success:function(response){
$('#success').html(response);
}
});
var form=document.getElementById('frmBox').reset();
return false;
}
</script>
heres the php send:
<?php
$customer_name_error = $customer_email_error = $customer_phone_error = "";
$customer_name = $customer_email = $customer_phone = $customer_message= $success = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["customer_name"])) {
$customer_name_error = "Name is required";
} else {
$customer_name = test_input($_POST["customer_name"]);
if (!preg_match("/^[a-zA-Z ]*$/",$customer_name_)) {
$customer_name_error = "Only letters and white space allowed";
}
}
if (empty($_POST["customer_email"])) {
$customer_email_error = "Email is required";
} else {
$customer_email = test_input($_POST["customer_email"]);
if (!filter_var($customer_email, FILTER_VALIDATE_EMAIL)) {
$customer_email_error = "Invalid email format";
}
}
if (empty($_POST["customer_phone"])) {
$customer_phone_error = "Phone is required";
} else {
$customer_phone = test_input($_POST["customer_phone"]);
if (!preg_match("/^(\d[\s-]?)?[\(\[\s-]{0,2}?\d{3}[\)\]\s-]{0,2}?\d{3}[\s-]?\d{4}$/i",$customer_phone)) {
$customer_phone_error = "Invalid phone number";
}
}
if (empty($_POST["customer_message"])) {
$customer_message = "";
} else {
$customer_message = test_input($_POST["customer_message"]);
}
if ($customer_name_error == '' and $customer_email_error == '' and $customer_phone_error == '' ){
$customer_message_body = '';
unset($_POST['submit']);
foreach ($_POST as $key => $value){
$customer_message_body .= "$key: $value\n";
}
$to = 'gorilyawarfare#gmail.com';
$subject = 'Messages';
if (mail($to, $subject, $message)){
$success = "Message sent, thank you for contacting us!";
$customer_name = $customer_email = $customer_phone = $customer_message = '';
}
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
I'm trying to implement reCaptcha into my existing contact form, and have hit a snag with where exactly (notice I used the word exactly) to place the server side PHP code within my page.
I've added the required PHP within the form with correct public key (and added the private key to the server side PHP).
I have the validation PHP for the form at the top of the same page as the form is on.
Existing validation code as follows:
<?php
// Set email variables
$email_to = 'myemailishere';
$email_subject = 'MY Enquiry TITLE IS HERE';
// Set required fields
$required_fields = array('fullname','email','comment');
// set error messages
$error_messages = array(
'fullname' => 'Please enter your Name.',
'email' => 'Please enter a valid Email.',
'comment' => 'Please enter a Message.'
);
// Set form status
$form_complete = FALSE;
// configure validation array
$validation = array();
// check form submittal
if(!empty($_POST)) {
// Sanitise POST array
foreach($_POST as $key => $value) $_POST[$key] = remove_email_injection(trim($value));
// Loop into required fields and make sure they match our needs
foreach($required_fields as $field) {
// the field has been submitted?
if(!array_key_exists($field, $_POST)) array_push($validation, $field);
// check there is information in the field?
if($_POST[$field] == '') array_push($validation, $field);
// validate the email address supplied
if($field == 'email') if(!validate_email_address($_POST[$field])) array_push($validation, $field);
}
// basic validation result
if(count($validation) == 0) {
// Prepare our content string
$email_content = 'New Website Comment: ' . "\n\n";
// simple email content
foreach($_POST as $key => $value) {
if($key != 'submit') $email_content .= $key . ': ' . $value . "\n";
}
// if validation passed ok then send the email
mail($email_to, $email_subject, $email_content);
// Update form switch
$form_complete = TRUE;
}
}
function validate_email_address($email = FALSE) {
return (preg_match('/^[^#\s]+#([-a-z0-9]+\.)+[a-z]{2,}$/i', $email))? TRUE : FALSE;
}
function remove_email_injection($field = FALSE) {
return (str_ireplace(array("\r", "\n", "%0a", "%0d", "Content-Type:", "bcc:","to:","cc:"), '', $field));
}
?>
And my Form code is this:
<div id="mainform">
<?php if($form_complete === FALSE): ?>
<form autocomplete="off" action="index.php#contact" method="post" id="comments_form">
<div class="row">
<div class="label">Your full name</div><!---end label--->
<div class="input">
<input type="text" id="fullname" class="detail" name="fullname" value="<?php echo isset($_POST['fullname'])? $_POST['fullname'] : ''; ?>" /><?php if(in_array('fullname', $validation)): ?><span class="error"><?php echo $error_messages['fullname']; ?></span><?php endif; ?>
</div><!---end input--->
</div><!---end row--->
<div class="row">
<div class="label">Your email address</div><!---end label--->
<div class="input">
<input type="text" id="email" class="detail" name="email" value="<?php echo isset($_POST['email'])? $_POST['email'] : ''; ?>" /><?php if(in_array('email', $validation)): ?><span class="error"><?php echo $error_messages['email']; ?></span><?php endif; ?>
</div><!---end input--->
</div><!---end row--->
<div class="row">
<div class="label">Your number? (if you'd like a call)</div><!---end label--->
<div class="input">
<input type="text" id="telephone" class="detail" name="telephone" value="<?php echo isset($_POST['telephone'])? $_POST['telephone'] : ''; ?>" />
</div><!---end input--->
</div><!---end row--->
<div class="row">
<div class="label">Your message</div><!---end label--->
<div class="input">
<textarea id="comment" name="comment" class="mess"><?php echo isset($_POST['comment'])? $_POST['comment'] : ''; ?></textarea><?php if(in_array('comment', $validation)): ?><span class="error"><?php echo $error_messages['comment']; ?></span><?php endif; ?>
</div><!---end input--->
</div><!---end row--->
<div class="row">
<div class="label">Prove you're Human</div><!---end label--->
<?php
require_once('recaptchalib.php');
$publickey = "your_public_key"; // public key omitted for purpose of stackeroverflow
echo recaptcha_get_html($publickey);
?>
</div><!---end row--->
<div class="submit">
<input type="submit" id="submit" name="submit" value="SEND MESSAGE" />
</div><!---end submit--->
</form>
<?php else: ?>
<p>Thank you, we've received your message.</p>
<?php endif; ?>
</div><!---end mainform--->
So...where do I stick this code (as in integrate the code into my existing validation php)?????:
<?php
require_once('recaptchalib.php');
$privatekey = "your_private_key";
$resp = recaptcha_check_answer ($privatekey,
$_SERVER["REMOTE_ADDR"],
$_POST["recaptcha_challenge_field"],
$_POST["recaptcha_response_field"]);
if (!$resp->is_valid) {
// What happens when the CAPTCHA was entered incorrectly
die ("The reCAPTCHA wasn't entered correctly. Go back and try it again." .
"(reCAPTCHA said: " . $resp->error . ")");
} else {
// Your code here to handle a successful verification
}
?>
Hope that makes sense and someone can help?
I am creating a form that sends the form's details to my email.
My custom field is:
My function.php
function getHotel_contact_number() {
global $wp_query;
$postid = $wp_query->post->ID;
$getHotel_contact_number = get_post_meta($postid, 'hotel_contact_number', true);
$getHotel_contact_number;
}
And my form is:
<?PHP
$errors = array();
if (isset($_POST["submit"])) {
$to = "myemail#email.com";
$subject = "This is my subject";
$hotel = get_permalink();
$hotel_contact_nmbr = getHotel_contact_number();
$headers = array('From: '.$_POST['sendername'].' <'.$_POST['senderEmail'].'>');
//Check the name and make sure that it isn't a blank/empty string.
if(empty($sender)){
//Blank string, add error to $errors array.
$errors['sendername'] = "Please enter your name!";
}
if(empty($senderEmail)){
//Blank string, add error to $errors array.
$errors['senderEmail'] = "Please enter your email!";
}
$mailBody = "<h3>Hotel Details</h3><br/>
$hotel<br/>
$hotel_contact_nmbr<br/>"
$mail_sent = wp_mail( $to, $subject, $mailBody, $headers );
}
if ($mail_sent) { ?>
<h1 style="color: #007f00;">Request sent.</h1>
<?php
} else {
?>
<form id="" name="" action="<?php echo get_permalink(); ?>" method="post">
<div class="label-input-wrapper">
<div class="form-label">Name</div>
<div class="form-input">
<input type="text" name="sendername" value="<?PHP if(!empty($errors)) { echo $sender;} ?>" />
<div class="error-msg">
<?php if(isset($errors['sendername'])) { echo '<span style="color: red">'.$errors['sendername'].'</span>'; } ?>
</div>
</div>
</div>
<div class="label-input-wrapper">
<div class="form-label">E-Mail</div>
<div class="form-input">
<input type="email" name="senderEmail" pattern="[a-z0-9._%+-]+#[a-z0-9.-]+\.[a-z]{2,4}$" required value="<?PHP if(!empty($errors)) { echo $senderEmail;} ?>" />
<div class="error-msg">
<?php if(isset($errors['senderEmail'])) { echo '<span style="color: red">'.$errors['senderEmail'].'</span>'; } ?>
</div>
</div>
</div>
<input type="submit" value="Submit" name="submit">
</form>
<?php
}
?>
But when the form is submitted I am getting just a blank value for hotel contact number. What I am doing wrong? How can get the proper custom filed value when the form is submitted?
Anyhow it's working fine if I use hidden fields for this as I mentioned here:
Have a look at the bottom area of that question where I mention about hidden fields.
Change function with following code:
function getHotel_contact_number() {
global $wp_query;
$postid = $wp_query->post->ID;
$getHotel_contact_number = get_post_meta($postid, 'hotel_contact_number', true);
return $getHotel_contact_number;
}