Form submit stopping other functions working with scrollify.move? - php

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);
});

Related

(PHP) trying to detect google recaptcha code failure

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>

Custom Page Template is not shown as page section in Wordpress twentyseventeen theme?

I created a page template and put it as the theme for a page. After that i have chosen this page as a page section in the twenty seventeen theme options but the content of this page is not shown just if you access the page directly and not as a page section.
<?php
/*
Template Name: Contact
*/
?>
<?php
if(isset($_POST['submitted'])) {
if(trim($_POST['contactName']) === '') {
$nameError = 'Please enter your name.';
$hasError = true;
} else {
$name = trim($_POST['contactName']);
}
if(trim($_POST['email']) === '') {
$emailError = 'Please enter your email address.';
$hasError = true;
} else if (!preg_match("/^[[:alnum:]][a-z0-9_.-]*#[a-z0-9.-]+\.[a-z]{2,4}$/i", trim($_POST['email']))) {
$emailError = 'You entered an invalid email address.';
$hasError = true;
} else {
$email = trim($_POST['email']);
}
if(trim($_POST['comments']) === '') {
$commentError = 'Please enter a message.';
$hasError = true;
} else {
if(function_exists('stripslashes')) {
$comments = stripslashes(trim($_POST['comments']));
} else {
$comments = trim($_POST['comments']);
}
}
if(!isset($hasError)) {
$emailTo = get_option('tz_email');
if (!isset($emailTo) || ($emailTo == '') ){
$emailTo = get_option('admin_email');
}
$subject = '[PHP Snippets] From '.$name;
$body = "Name: $name \n\nEmail: $email \n\nComments: $comments";
$headers = 'From: '.$name.' <'.$emailTo.'>' . "\r\n" . 'Reply-To: ' . $email;
wp_mail($emailTo, $subject, $body, $headers);
$emailSent = true;
}
} ?>
<?php get_header(); ?>
<div id="container">
<div id="content">
<?php if (have_posts()) : while (have_posts()) : the_post(); ?>
<div <?php post_class() ?> id="post-<?php the_ID(); ?>">
<h1 class="entry-title"><?php the_title(); ?></h1>
<div class="entry-content">
<?php if(isset($emailSent) && $emailSent == true) { ?>
<div class="thanks">
<p>Thanks, your email was sent successfully.</p>
</div>
<?php } else { ?>
<?php the_content(); ?>
<?php if(isset($hasError) || isset($captchaError)) { ?>
<p class="error">Sorry, an error occured.<p>
<?php } ?>
<form action="<?php the_permalink(); ?>" id="contactForm" method="post">
<ul class="contactform">
<li>
<label for="contactName">Name:</label>
<input type="text" name="contactName" id="contactName" value="<?php if(isset($_POST['contactName'])) echo $_POST['contactName'];?>" class="required requiredField" />
<?php if($nameError != '') { ?>
<span class="error"><?=$nameError;?></span>
<?php } ?>
</li>
<li>
<label for="email">Email</label>
<input type="text" name="email" id="email" value="<?php if(isset($_POST['email'])) echo $_POST['email'];?>" class="required requiredField email" />
<?php if($emailError != '') { ?>
<span class="error"><?=$emailError;?></span>
<?php } ?>
</li>
<li><label for="commentsText">Message:</label>
<textarea name="comments" id="commentsText" rows="20" cols="30" class="required requiredField"><?php if(isset($_POST['comments'])) { if(function_exists('stripslashes')) { echo stripslashes($_POST['comments']); } else { echo $_POST['comments']; } } ?></textarea>
<?php if($commentError != '') { ?>
<span class="error"><?=$commentError;?></span>
<?php } ?>
</li>
<li>
<input type="submit">Send email</input>
</li>
</ul>
<input type="hidden" name="submitted" id="submitted" value="true" />
</form>
<?php } ?>
</div><!-- .entry-content -->
</div><!-- .post -->
<?php endwhile; endif; ?>
</div><!-- #content -->
</div><!-- #container -->
<?php get_sidebar(); ?>
<?php get_footer(); ?>
I hope you can help me guys. Thanks in advance! :)
Edit:
The website with the custom page template is displayed when you access the page directly like for example http://example.com/testing.
direct link
But if you want to set it as a page section in the twentyseventeen theme under the theme options the space, where the custom template should appear, is blank. This is the case if you access it via http://example.com. The site is a onepager and the testing page with the custom page template is a section of it.
front page
2nd Edit:
I set the custom page as a page section by just setting it in the theme options.
theme options of twentyseventeen theme
You're trying to use wordpress functions out of wordpress. Place this code require_once($_SERVER['DOCUMENT_ROOT'] . '/wp-load.php'); directly to next line of opening php tag <?php at 8th line of your code.
This may not work if your wordpress installation is on some folder of your main server directory. Then you can try this one:
//place this at the same position, as I mentioned above
$needPath = realpath(__DIR__ . '/../../..');
require_once($needPath . '/wp-load.php');
Used solution from here to go several levels up in the filesystem. Because we need to go to main wordpress installation folder from {wp-main-folder}/wp-content/themes/twentyseventeen/{your-file}, we should to go 3 levels up for reaching wp-load.php file.
EDIT
Also, it will be useful to check, if your page is called from/out of your wordpress installation. So, you can use this solution for it:
//place this to the same place as described above
if(!defined(ABSPATH)) {
$needPath = realpath(__DIR__ . '/../../..');
require_once($needPath . '/wp-load.php');
}
Tested and working
Edit: more detailed
<?php
/*
Template Name: Contact
*/
if(!defined(ABSPATH)) {
$needPath = realpath(__DIR__ . '/../../..');
require_once($needPath . '/wp-load.php');
}
if(isset($_POST['submitted'])) {
if(trim($_POST['contactName']) === '') {
$nameError = 'Please enter your name.';
$hasError = true;
} else {
$name = trim($_POST['contactName']);
}
if(trim($_POST['email']) === '') {
$emailError = 'Please enter your email address.';
$hasError = true;
} else if (!preg_match("/^[[:alnum:]][a-z0-9_.-]*#[a-z0-9.-]+\.[a-z]{2,4}$/i", trim($_POST['email']))) {
$emailError = 'You entered an invalid email address.';
$hasError = true;
} else {
$email = trim($_POST['email']);
}
if(trim($_POST['comments']) === '') {
$commentError = 'Please enter a message.';
$hasError = true;
} else {
if(function_exists('stripslashes')) {
$comments = stripslashes(trim($_POST['comments']));
} else {
$comments = trim($_POST['comments']);
}
}
if(!isset($hasError)) {
$emailTo = get_option('tz_email');
if (!isset($emailTo) || ($emailTo == '') ){
$emailTo = get_option('admin_email');
}
$subject = '[PHP Snippets] From '.$name;
$body = "Name: $name \n\nEmail: $email \n\nComments: $comments";
$headers = 'From: '.$name.' <'.$emailTo.'>' . "\r\n" . 'Reply-To: ' . $email;
wp_mail($emailTo, $subject, $body, $headers);
$emailSent = true;
}
} ?>
<?php get_header(); ?>
<div id="container">
<div id="content">
<?php if (have_posts()) : while (have_posts()) : the_post(); ?>
<div <?php post_class() ?> id="post-<?php the_ID(); ?>">
<h1 class="entry-title"><?php the_title(); ?></h1>
<div class="entry-content">
<?php if(isset($emailSent) && $emailSent == true) { ?>
<div class="thanks">
<p>Thanks, your email was sent successfully.</p>
</div>
<?php } else { ?>
<?php the_content(); ?>
<?php if(isset($hasError) || isset($captchaError)) { ?>
<p class="error">Sorry, an error occured.<p>
<?php } ?>
<form action="<?php the_permalink(); ?>" id="contactForm" method="post">
<ul class="contactform">
<li>
<label for="contactName">Name:</label>
<input type="text" name="contactName" id="contactName" value="<?php if(isset($_POST['contactName'])) echo $_POST['contactName'];?>" class="required requiredField" />
<?php if($nameError != '') { ?>
<span class="error"><?=$nameError;?></span>
<?php } ?>
</li>
<li>
<label for="email">Email</label>
<input type="text" name="email" id="email" value="<?php if(isset($_POST['email'])) echo $_POST['email'];?>" class="required requiredField email" />
<?php if($emailError != '') { ?>
<span class="error"><?=$emailError;?></span>
<?php } ?>
</li>
<li><label for="commentsText">Message:</label>
<textarea name="comments" id="commentsText" rows="20" cols="30" class="required requiredField"><?php if(isset($_POST['comments'])) { if(function_exists('stripslashes')) { echo stripslashes($_POST['comments']); } else { echo $_POST['comments']; } } ?></textarea>
<?php if($commentError != '') { ?>
<span class="error"><?=$commentError;?></span>
<?php } ?>
</li>
<li>
<input type="submit">Send email</input>
</li>
</ul>
<input type="hidden" name="submitted" id="submitted" value="true" />
</form>
<?php } ?>
</div><!-- .entry-content -->
</div><!-- .post -->
<?php endwhile; endif; ?>
</div><!-- #content -->
</div><!-- #container -->
<?php get_sidebar(); ?>
<?php get_footer(); ?>
For calling this template from wordpress. you need to call it like( if your website url is http://example.com ):
Create page from wordpress dashboard and choose from the list template on the right side of create page section instead of Default Template the one you want to use:
After it( dont forget to add page title ) save page and go to the url, provided there. If page don't have parent, or permalinks are as ?p=123 then you should access that page like here: http://example.com/your-page-title.
If you're going to access that template directly, you should write url as http://example.com/wp-content/themes/twentyseventeen/your-template-filename.php. This example provided as your template is directly in your twentyseventeen theme folder.

Is there a way to know if my php script for sending form via email worked?

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;
}
?>

How to get a wordpress post custom filed value and assign it to a variable?

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;
}

Wordpress Custom Contact Form Not Working

I am trying to create a custom contact form page for my Wordpress theme. However on my way to finishing my codes the error message on my page won't show up.
Also, I am running on a localhost computer for testing this custom page and it seems it won't send my message to the ADMIN EMAIL that was set on my Wordpress Installation.
Here's the snippet on my WP Custom Contact Form:
<?php
/* Template Name: Contact Page */
?>
<?php
// Function for email address validation
function isEmail($verify_email) {
return(preg_match("/^[-_.[:alnum:]]+#((([[:alnum:]]|[[:alnum:]][[:alnum:]-]*[[:alnum:]])\.)+(ad|ae|aero|af|ag|ai|al|am|an|ao|aq|ar|arpa|as|at|au|aw|az|ba|bb|bd|be|bf|bg|bh|bi|biz|bj|bm|bn|bo|br|bs|bt|bv|bw|by|bz|ca|cc|cd|cf|cg|ch|ci|ck|cl|cm|cn|co|com|coop|cr|cs|cu|cv|cx|cy|cz|de|dj|dk|dm|do|dz|ec|edu|ee|eg|eh|er|es|et|eu|fi|fj|fk|fm|fo|fr|ga|gb|gd|ge|gf|gh|gi|gl|gm|gn|gov|gp|gq|gr|gs|gt|gu|gw|gy|hk|hm|hn|hr|ht|hu|id|ie|il|in|info|int|io|iq|ir|is|it|jm|jo|jp|ke|kg|kh|ki|km|kn|kp|kr|kw|ky|kz|la|lb|lc|li|lk|lr|ls|lt|lu|lv|ly|ma|mc|md|me|mg|mh|mil|mk|ml|mm|mn|mo|mp|mq|mr|ms|mt|mu|museum|mv|mw|mx|my|mz|na|name|nc|ne|net|nf|ng|ni|nl|no|np|nr|nt|nu|nz|om|org|pa|pe|pf|pg|ph|pk|pl|pm|pn|pr|pro|ps|pt|pw|py|qa|re|ro|ru|rw|sa|sb|sc|sd|se|sg|sh|si|sj|sk|sl|sm|sn|so|sr|st|su|sv|sy|sz|tc|td|tf|tg|th|tj|tk|tm|tn|to|tp|tr|tt|tv|tw|tz|ua|ug|uk|um|us|uy|uz|va|vc|ve|vg|vi|vn|vu|wf|ws|ye|yt|yu|za|zm|zw)$|(([0-9][0-9]?|[0-1][0-9][0-9]|[2][0-4][0-9]|[2][5][0-5])\.){3}([0-9][0-9]?|[0-1][0-9][0-9]|[2][0-4][0-9]|[2][5][0-5]))$/i",$verify_email));
}
$error_name = false;
$error_email = false;
$error_subject = false;
$error_message = false;
if (isset($_POST['submit'])) {
// Initialize the variables
$contact_name = '';
$contact_email = '';
$contact_subject = '';
$contact_message = '';
// Get the name
if (trim($_POST['contact_name']) === '') {
$error_name = true;
} else {
$name = trim($_POST['contact_name']);
}
// Get the email
if (trim($_POST['contact_email']) === '' || !isEmail($_POST['contact_email'])) {
$error_email = true;
} else {
$email = trim($_POST['contact_email']);
}
// Check if we have errors
if (!$error_name && !$error_email && !$error_subject && !$error_message) {
// Get the receiver email from the WP admin panel
$receiver_email = get_option('admin_email');
$subject = "Message from $contact_name";
$body = "You have a new quote request from $contact_name. Project details:" . PHP_EOL . PHP_EOL;
$body .= PHP_EOL . PHP_EOL;
$headers = "From: $contact_email" . PHP_EOL;
$headers .= "Reply-To: $contact_email" . PHP_EOL;
$headers .= "MIME-Version: 1.0" . PHP_EOL;
$headers .= "Content-type: text/plain; charset=utf-8" . PHP_EOL;
$headers .= "Content-Transfer-Encoding: quoted-printable" . PHP_EOL;
// If all is good, we send the email
if (mail($receiver_email, $subject, $body, $headers)) {
$email_sent = true;
} else {
$email_sent_error = true;
}
}
}
?>
<?php get_header(); ?>
<!-- BLOG AREA -->
<section>
<hr class="no-margin" />
<div class="blog-container section-content">
<div class="container">
<div class="row">
<div class="col-md-8">
<div class="box-layer custom-padding">
<div class="align-center">
<h2>We want to hear from you!</h2>
<p>If you are seeking to contact us, please fill up the form below. If you want to advertise or be partner with us just inform us on the message box below. </p>
<p>Thank you so much for your support!
<br/>We really appreciate!</p>
<?php if (isset($email_sent) && $email_sent == true) : ?>
<h2>Success!</h2>
<p>You have successfully sent the quote request. I'll get back to you as soon as possible.</p>
<?php elseif (isset($email_sent_error) && $email_sent_error == true) : ?>
<h2>There was an error!</h2>
<p>Unfortunately, there was an error while trying to send the email. Please try again.</p>
<?php else : ?>
<form action="<?php the_permalink(); ?>" method="POST" class="general-form" novalidate>
<p <?php if ($error_name) echo 'class="error"'; ?>><input name="contact_name" id="contact_name" class="form-control" placeholder="Your Name.." type="text" value="<?php if (isset($_POST['contact_name'])) echo $_POST['contact_name']; ?>" /></p>
<p <?php if ($error_email) echo 'class="error"'; ?>><input name="contact_email" id="contact_email" class="form-control" placeholder="Your Email.." type="email" value="<?php if (isset($_POST['contact_email'])) echo $_POST['contact_email']; ?>" /></p>
<p <?php if ($error_subject) echo 'class="error"'; ?>><input name="contact_subject" id="contact_subject" class="form-control" placeholder="Your Subject.." type="text" value="<?php if (isset($_POST['contact_subject'])) echo $_POST['contact_subject']; ?>"/></p>
<p <?php if ($error_message) echo 'class="error"'; ?>><textarea name="contact_message" id="contact_message" class="form-control" placeholder="Write your comment here.." rows="4" cols="100"><?php if (isset($_POST['contact_message'])) echo $_POST['contact_message']; ?></textarea></p>
<input class="btn btn-primary no-border" name="submit" type="submit" id="submit" value="Send Message">
</form>
<?php endif; ?>
</div>
</div>
<!-- RELATED ARTICLE AREA -->
</div>
<aside>
<!-- SIDEBAR AREA -->
<div class="col-md-3 col-md-offset-1 margin-sidebar">
<?php get_sidebar(); ?>
</div>
</aside>
</section>
<?php get_footer(); ?>
Any idea? or Is there a way you can correct my code if you see some errors?
To get you started
Make sure WP_DEBUG is set to true on your wp-config.php file.
You can get the last errors from mail() (answered here)
Use wordpress' functions if available, in this case wp_mail is at your disposal.
There are wordpress plugins such as gravity forms or contact form 7 which can accomplish the task.
Use filters and actions.
Had to post as an answer, couldn't comment yet.
HTH
If you would like to get the admin email address, you have to do it with:
$bloginfo = get_bloginfo( 'admin_email' );
get_option('admin_email') is only works when you save anything to that in the Theme Setup, probably it is empty now.
By the way, you can find many of professional, ready to use solution, like WordPress Contact Form Slider
<?php
/*
Plugin Name:Contact Form Plugin
Plugin URI: http://example.com
Description: Simple non-bloated WordPress Contact Form
Version: 1.0
Author: Agbonghama Collins
Author URI: http://w3guy.com
*/
if ( !defined('ABSPATH') )
define('ABSPATH', dirname(__FILE__) . '/');
define( 'MY_PLUGIN_PATH', plugin_dir_path( __FILE__ ) );
include( MY_PLUGIN_PATH . 'form/form.php');
include( MY_PLUGIN_PATH . 'admin/admin-menu.php');
include( MY_PLUGIN_PATH . 'database/table.php');
?>
Form.php
====================
<?php
function form()
{
echo '<form action="'.esc_url($_SERVER['REQUEST_URI']).'" method="post">';
echo '<p>';
echo 'Your First Name:';
echo '<br/>';
echo '<input type="text" name="fname" required/>';
echo '<br/>';
echo 'your Email-Id:';
echo '<br/>';
echo '<input type="email" name="email" required/>';
echo '<br/>';
echo 'Your Subject:';
echo '<br/>';
echo '<input type="text" name="subject" required/>';
echo '<br/>';
echo 'Your Message:';
echo '<br/>';
echo '<textarea name="message" cols="30" rows="4" required></textarea>';
echo '<br/>';
echo '<input type="submit" name="submit" value="Submit"/>';
echo '</form>';
}
if(isset($_REQUEST['submit']))
{
$name = $_POST['fname'];
$email = $_POST['email'];
$subject=$_POST['subject'];
$msg=$_POST['message'];
function insertuser($name,$email,$msg,$subject){
global $wpdb;
$table_name = $wpdb->prefix . "contactinfo";
$wpdb->insert($table_name, array('name' => $name, 'email' => $email , 'message'=> $msg , 'subject' => $subject) );
}
insertuser($name,$email,$msg,$subject);
}
function shortcode()
{
form();
}
add_shortcode('contact-form','shortcode');
?>
table.php
===================
<?php
global $wpdb;
$table_name = $wpdb->prefix . "contactinfo";
$charset_collate = $wpdb->get_charset_collate();
if( $wpdb->get_var ('SHOW TABLE LINK' .$table_name) != $table_name )
{
$sql = "CREATE TABLE $table_name (
id mediumint(9) NOT NULL AUTO_INCREMENT,
name varchar(50) NOT NULL,
email varchar(40) NOT NULL,
message text NOT NULL,
subject text NOT NULL,
PRIMARY KEY (id)
) $charset_collate;";
require_once( ABSPATH . 'wp-admin/includes/upgrade.php' );
dbDelta( $sql );
}
?>

Categories