WordPress PHP Form Won't Send - php

I'm probably missing something really simple here or have a little typo in my code but the PHP form I've created for a WordPress site I'm building won't send. If there are errors in the form, the validation works (except for if you just enter a name) but when you fill in the form correctly and click submit, it simply goes to the page it's meant to for processing and says 'Sorry, no posts matched your criteria.'. Plus the mail doesn't get sent.
EDIT
The link to the dev site is http://dev.garethdaine.com/inkframe/.
The page for processing does exist. Here's my code:
Form Code
<form name="quick-contact" class="quick-contact" method="post" action="<?php bloginfo('url'); ?>/get-in-touch/">
<h3>Request a Call Back</h3>
<h4><label for="name">Name</label></h4>
<input id="name" name="name" type="text" />
<h4><label for="email">Email</label></h4>
<input id="email" name="email" type="text" />
<h4><label for="phone">Phone</label></h4>
<input id="phone" name="phone" type="text" />
<input id="submit" type="submit" value="Submit" />
<input type="hidden" name="submitted" id="submitted" value="true" />
<input type="hidden" name="required" id="required" class="required" />
</form>
PHP Code
<?php
/*
* Template Name: Contact
*/
if( isset( $_POST['submitted'] ) ) {
$to = get_option( 'admin_email' );
if( trim( $_POST['name'] ) === '' ) {
$nameError = 'You did not enter your name.';
$hasError = true;
} else {
$name = trim( $_POST['name'] );
}
if( trim( $_POST['email'] ) === '' ) {
$emailError = 'You did not 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['phone'] ) === '' ) {
$phoneError = 'You did not enter your telephone number.';
$hasError = true;
} else if( !is_numeric( $_POST['phone'] ) ) {
$phoneError = 'You have entered an invalid phone number.';
$hasError = true;
} else {
$phone = trim( $_POST['phone'] );
}
if( !empty( $_POST['required'] ) ) {
$requiredError = 'You appear to be a robot. If you are human, please try again.';
$hasError = true;
}
if( !isset( $hasError ) ) {
$subject = 'Call Back Request from ' . $name;
$body = "Name: $name \n\nEmail: $email \n\nPhone: $phone";
$headers = 'From: ' . $name . ' <' . $emailTo . '>' . "\r\n" . 'Reply-To: ' . $email;
wp_mail( $to, $subject, $body, $headers );
$emailSent = true;
}
}
?>
<?php get_header(); ?>
<div class="content" role="main">
<?php if ( have_posts() ) while ( have_posts() ) : the_post(); ?>
<div id="post-<?php the_ID(); ?>" <?php post_class(); ?>>
<h1 class="entry-title"><?php the_title(); ?></h1>
<div class="entry-content">
<?php if( isset( $emailSent ) && $emailSent == true ) { ?>
<p><strong>Your message has been sent successfully. Someone will be in touch shortly. Thanks.</strong></p>
<?php the_content(); ?>
<?php } else { ?>
<?php if( isset( $hasError ) ) { ?>
<p class="error">Sorry, an error has occured.<p>
<ul>
<?php if( $nameError != '' ) { ?>
<li>
<span class="error"><?php echo $nameError; ?></span>
</li>
<?php } ?>
<?php if( $emailError != '' ) { ?>
<li>
<span class="error"><?php echo $emailError; ?></span>
</li>
<?php } ?>
<?php if( $phoneError != '' ) { ?>
<li>
<span class="error"><?php echo $phoneError; ?></span>
</li>
<?php } ?>
<?php if( !empty( $requiredError ) ) { ?>
<li>
<span class="error"><?php echo $requiredError; ?></span>
</li>
<?php } ?>
</ul>
<?php } ?>
<?php the_content(); ?>
<?php } ?>
</div>
</div>
<?php endwhile; ?>
</div>
<?php get_sidebar(); ?>
<?php get_footer(); ?>

OK Guys,
Looks like I've finally figured out the problem. All the code, in all it's variations was fine and works, except for one tiny thing. The variable '$name' is used by the WordPress system to display the blog name, and as I was using that as my variable for the name field on my form it was causing issues. Who knew.
Anyway, I simply changed it to use '$fullName' and changed the id and name attributes on the form to 'full-name' and everything worked great.
Thanks to #maiorano84 for pointing me in the right direction to debug the problem.
Anyway, below is my amended code, so others can make use of it.
Form Code
<form name="quick-contact" class="quick-contact" method="post" action="<?php bloginfo( 'url' ); ?>/get-in-touch/">
<h3>Request a Call Back</h3>
<h4><label for="full-name">Full Name</label></h4>
<input id="full-name" name="full-name" type="text" />
<h4><label for="email">Email</label></h4>
<input id="email" name="email" type="text" />
<h4><label for="phone">Phone</label></h4>
<input id="phone" name="phone" type="text" />
<input id="submit" type="submit" value="Submit" />
<input type="hidden" name="required" id="required" class="required" />
</form>
PHP Code
<?php
/*
* Template Name: Contact
*/
?>
<?php get_header(); ?>
<?php
if( $_SERVER['REQUEST_METHOD'] == "POST" ) {
$to = get_option( 'admin_email' );
if( trim( $_POST['full-name'] ) === '' ) {
$nameError = 'You did not enter your name.';
$hasError = true;
} else {
$fullName = trim( $_POST['full-name'] );
}
if( trim( $_POST['email'] ) === '' ) {
$emailError = 'You did not 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['phone'] ) === '' ) {
$phoneError = 'You did not enter your telephone number.';
$hasError = true;
} else if( !is_numeric( $_POST['phone'] ) ) {
$phoneError = 'You have entered an invalid phone number.';
$hasError = true;
} else {
$phone = trim( $_POST['phone'] );
}
if( !empty( $_POST['required'] ) ) {
$requiredError = 'You appear to be a robot. If you are human, please try again.';
$hasError = true;
}
if( !isset( $hasError ) ) {
if ( !isset( $to ) || ( $to == '' ) ) {
$to = get_option( 'admin_email' );
}
$subject = 'Call Back Request from ' . $fullName;
$body = "Name: $fullName <br />Email: $email <br />Phone: $phone";
$headers[] = 'From: ' . $fullName . ' <' . $email . '>';
$headers[] = 'Reply-To: ' . $email;
$headers[] = 'Content-type: text/html; charset=utf-8';
wp_mail( $to, $subject, $body, $headers );
$emailSent = true;
}
}
?>
<div class="content" role="main">
<?php if ( have_posts() ) while ( have_posts() ) : the_post(); ?>
<div id="post-<?php the_ID(); ?>" <?php post_class(); ?>>
<h1 class="entry-title"><?php the_title(); ?></h1>
<div class="entry-content">
<?php if( isset( $emailSent ) && $emailSent == true ) { ?>
<p><strong>Your message has been sent successfully. Someone will be in touch shortly. Thanks.</strong></p>
<?php } else { ?>
<?php var_dump($headers); ?>
<?php if( isset( $hasError ) ) { ?>
<p class="error">Sorry, an error has occured.<p>
<ul>
<?php if( $nameError != '' ) { ?>
<li>
<span class="error"><?php echo $nameError; ?></span>
</li>
<?php } ?>
<?php if( $emailError != '' ) { ?>
<li>
<span class="error"><?php echo $emailError; ?></span>
</li>
<?php } ?>
<?php if( $phoneError != '' ) { ?>
<li>
<span class="error"><?php echo $phoneError; ?></span>
</li>
<?php } ?>
<?php if( !empty( $requiredError ) ) { ?>
<li>
<span class="error"><?php echo $requiredError; ?></span>
</li>
<?php } ?>
</ul>
<?php } ?>
<?php } ?>
<?php the_content(); ?>
</div>
</div>
<?php endwhile; ?>
</div>
<?php get_sidebar(); ?>
<?php get_footer(); ?>

Tell me if is arrived an email, if not change
$to = get_option( 'admin_email' );
with
$to = your#email.com; //exemple
When you have changed try and tell me if it works ;)

Related

When contact form button is clicked, site redirects to a custom post enrty

I've got this wordpress site with a custom post type, called reviews, loop and a contact form on a page. When I click on the submit button on the contact page, reguardless if the form contents matches the regex, it redirects the page to /reviewa/random name
I've removed the "reviews" part of the website and the form works.
What I would like to happen is to have the form send the email, without redirecting the site to /reviews/randomName
$(function() {
var re = /^(([^<>()[\]\\.,;:\s#\"]+(\.[^<>()[\]\\.,;:\s#\"]+)*)|(\".+\"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
$('#contact-form').submit(function(e) {
$clientName = $("#contactName").val();
var valid = true;
// Remove any confirmation messages
$('p.confirmation').remove();
// Validate all fields that have a class of .required-field
$('.required-field').each(function() {
// Remove error class from all inputs and textareas and delete error messages before checking form again
$(this).removeClass('error').next('p').remove();
if ($(this).val().trim() === '' && $(this).attr('id') != 'email') {
$(this).addClass('error').parent().append('<p class="error">Please enter a ' + $(this).prev().html().toLowerCase() + '</p>');
valid = valid && false;
} else if ($(this).attr('id') === 'email') {
if (!$(this).val().trim().match(re)) {
$(this).addClass('error').parent().append('<p class="error">Please enter a valid email address</p>');
valid = valid && false;
}
}
});
if (valid) {
var formInput = $(this).serialize();
$.post($(this).attr('action'), formInput, function(data) {
$('#contact-form').before('<p class="confirmation">Thanks ' + $clientName + ', your email was successfully sent. We will be in touch soon.</p>');
_gaq.push(['_trackEvent', 'Contact form', 'Contact form submitted']);
});
}
e.preventDefault();
});
});
<div id="reviews">
<h2>Our reviews</h2>
<div id="slider" class="flex-container">
<div class="flexslider">
<ul class="slides">
<?php $new = new WP_Query('post_type=reviews& posts_per_page=-1');
while ($new->have_posts()) : $new->the_post(); ?>
<li>
<?php echo the_post_thumbnail('portfolio-thumb');?>
<span class="review"> <?php the_content(); ?></span>
<span class="name"> <?php the_title(); ?></span>
</li>
<?php endwhile;?>
</ul>
</div>
</div>
</div>
<div id="contact">
<h2>To contact the instructor, plese enter your details below</h2>
<?php
if($_SERVER['REQUEST_METHOD'] == "POST" && isset($_POST['submitted'])){
//Check name
if(trim($_POST['contactName']) === '') {
$nameError = true;
$hasError = true;
}else{
$name = trim($_POST['contactName']);
}
//Check company name
if(trim($_POST['companyName']) === '') {
$companyNameError = true;
$companyNameError = true;
}else{
$companyName = trim($_POST['companyName']);
}
//Check address
if(trim($_POST['address']) === '') {
$addressError = true;
$addressError = true;
}else{
$address = trim($_POST['address']);
}
// Check email address exists and is valid
if(trim($_POST['email']) === '') {
$emailError = 'Please enter your email address.';
$hasError = true;
}else if (!eregi("^[A-Z0-9._%-]+#[A-Z0-9._%-]+.[A-Z]{2,4}$",trim($_POST['email']))){
$emailError = 'You entered an invalid email address.';
$hasError = true;
}else{
$email = trim($_POST['email']);
}
if(trim($_POST['telNumber']) === '') {
$telError = true;
$hasError = true;
}else{
$telephone = trim($_POST['telNumber']);
}
//Check message
if(trim($_POST['message']) === ''){
$messageError = true;
$hasError = true;
}else{
$message = stripslashes(trim($_POST['message']));
}
//If there is no error, send the email
if(!isset($hasError)){
$emailTo = 'randomEmail#mail.com';
$subject = 'Contact from the Contact Us page';
$body = "Name: $name \n Email: $email \n Telephone: $telephone \n Poxtcode: $address . \n Message:\n$message";
$headers = 'From: randomWebsite.com, <'.$emailTo.'>' . "\n" . "\n" .'Reply-To: ' . $email;
ssmtp($emailTo, $subject, $body, $headers);
$emailSent = true;
}
}
?>
<?php if($emailSent == true) { ?>
<p class="confirmation">Thanks,
<?php echo $name;?>, your email was successfully sent. We will be in touch soon.</p>
<?php } ?>
<form action="<?php the_permalink(); ?>" id="contact-form" method="post" novalidate>
<ul>
<li>
<input type="text" placeholder="Name (required)" name="contactName" id="contactName" value="<?php if(isset($_POST['contactName'])){echo $_POST['contactName'];} ?>" class="required-field" />
<?php if($nameError) { ?>
<p class="error">Please enter your name.</p>
<?php } ?>
</li>
<li>
<input type="text" placeholder="Postcode (required)" name="address" id="address" value="<?php if(isset($_POST['address'])){echo $_POST['address'];} ?>" class="required-field" />
<?php if($addressError) { ?>
<p class="error">Please enter your postcode.</p>
<?php } ?>
</li>
<li>
<input type="tel" placeholder="Mobile number (required)" name="telNumber" id="telNumber" value="<?php if(isset($_POST['telNumber'])){echo $_POST['telNumber'];} ?>" />
<?php if($telError) { ?>
<p class="error">Please enter your mobile number.</p>
<?php } ?>
</li>
<li>
<input type="email" placeholder="Email (required)" name="email" id="email" value="<?php if(isset($_POST['email'])){echo $_POST['email'];} ?>" class="required-field" />
<?php if($emailError) { ?>
<p class="error">
<?php echo $emailError;?>
</p>
<?php } ?>
</li>
<li class="textarea">
<textarea name="message" placeholder="Message (required)" id="message" rows="20" cols="30" class="required-field"><?php if(isset($_POST['message'])){echo stripslashes($_POST['message']);} ?></textarea>
<?php if($messageError) { ?>
<p class="error">Please enter a message.</p>
<?php } ?>
</li>
<li>
<input type="hidden" id="submitted" name="submitted" />
<button class="button" ">Send</button>
</li>
</ul>
</form>
</div>

Login Form Reappearing on Every Page

We have an infusionsoft login form modal on every page. When the user logs in, the modal is hidden and the information on the page is shown, and it stays shown on refresh. However, when the user navigates to another page, the login form reappears, even though the cookies from the login are still there. Here is the code of user-auth.php:
<?php
add_action( 'init', 'user_auth' );
/**
*
*
*/
function user_auth()
{
if( !isset( $_POST['user-auth'] ) ) {
return;
}
$page_id = 6;
$code = get_field( 'access_code', $page_id );
$v_username = isset( $_POST['entryemail'] ) ? $_POST['entryemail'] : '';
$v_value = isset( $_POST['entrycode'] ) ? $_POST['entrycode'] : '';
$v_time = isset( $_POST['remember'] ) ? $_POST['remember'] : 0;
$infusion = new Infusion();
$user = $infusion->findByEmail( $v_username );
if( $user && ( $v_value == $code ) ) {
$time = $v_time ? strtotime('+1 year') : strtotime('+3 day');
$md5 = user_auth_user_save( $user );
$url = parse_url( site_url() );
$path = isset( $url['path'] ) ? $url['path'] : '';
setcookie( 'website_login', $md5, $time, $path, $url['host'] );
$GLOBALS['localpopup'] = true;
}
elseif( $user ) {
$GLOBALS['localpopup'] = 'Invalid access code.';
}
else {
$GLOBALS['localpopup'] = 'Your email cannot be found.';
}
}
the form (login.php):
<?php
$email = isset( $_POST['entryemail'] ) ? $_POST['entryemail'] : '';
$code = isset( $_POST['entrycode'] ) ? $_POST['entrycode'] : '';
$remember = isset( $_POST['remember'] ) ? $_POST['remember'] : false;
$error = '';
if( isset( $GLOBALS['localpopup'] ) ) {
$error = $GLOBALS['localpopup'];
}
?>
<div class="form-code-wraper" id="code-login">
<span class="logo-popup"><img src="<?php echo THEMEURL ?>images/logo.png" alt="Pointy"/></span>
<h1>Welcome</h1>
<h2>Please enter your access code</h2>
<form accept-charset="UTF-8" action="" class="entry-form" method="POST">
<div class="input-holder-popup enter-code clearfix">
<div class="input-row clearfix">
<label for="entryemail">Email: </label>
<input class="field-input-container" id="entryemail" name="entryemail" type="email" dir="ltr" required value="<?php echo $email ?>"/>
</div>
<div class="input-row clearfix">
<label for="entrycode">Code: </label>
<input class="field-input-container" id="entrycode" name="entrycode" type="text" required value="<?php echo $code ?>"/>
</div>
<div class="input-row clear remember-input">
<input type="checkbox" id="remember" name="remember" value="1" <?php if( $remember ) : ?> checked="checked"<?php endif ?>/> <label for="remember">Remember me</label>
</div>
</div>
<div class="buttons send-button">
<input type="submit" name="user-auth" value="Enter" id="user-auth" />
</div>
</form>
<div class="send-info">
<?php if( $error ) : ?><div class="error-message"><?php echo $error ?></div><?php endif ?>
No code? Click here
</div>
</div>
popup.php:
<?php
if(is_page('282')){
return;
}else {
if( user_auth_popup_hide() ) {
return;
}
}
?>
<div id="light" class="white_content">
<?php get_template_part( 'blocks/popup/login' ) ?>
<?php get_template_part( 'blocks/popup/register' ) ?>
</div>
<div id="fade" class="black_overlay"></div>
function user_auth_popup_hide()
{
$localpopup = isset( $GLOBALS['localpopup'] ) && ( $GLOBALS['localpopup'] === true );
$cookie = isset( $_COOKIE['website_login'] );
$special_page = in_array( get_the_ID(), array(
169,
172,
) );
return $localpopup || $cookie || $special_page;
}
SOLVED:
This was not a code issue but rather an issue of having caching installed that was blocking auth cookies.
small bug in code.... instead of using
$url = parse_url( site_url() );
$path = isset( $url['path'] ) ? $url['path'] : '';
The cookie needs to be set with
setcookie( 'website_login', $md5, $time, '/', 'websitedomainname.com' );
I had tried '/' before as the path and it was not working, so the website domain name was essential in this case.

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.

Redirect to Home page after registration in Wordpress Workscout theme

I am working on a wordpress job portal. The problem that I am facing is that. The functionality of the registration and login form are; when a user registers, an email is generated to their registered email id with the password for their account.And the the registered user has to login using those credentials, but after every user registers for the site, the site directly logs the user in. I want the site to redirect to home or specific page after a user registers for the first time.
Registration Function
function workscout_registration_form() {
// only show the registration form to non-logged-in members
if(!is_user_logged_in()) {
// check to make sure user registration is enabled
$registration_enabled = get_option('users_can_register');
// only show the registration form if allowed
if($registration_enabled) { ?>
<form method="post" class="register workscout_form">
<?php do_action( 'woocommerce_register_form_start' ); ?>
<?php if ( 'no' === get_option( 'woocommerce_registration_generate_username' ) ) : ?>
<p class="form-row form-row-wide">
<label for="reg_username"><?php _e( 'Username', 'workscout' ); ?> <span class="required">*</span>
<i class="ln ln-icon-Male"></i>
<input type="text" class="input-text" name="username" id="reg_username" value="<?php if ( ! empty( $_POST['username'] ) ) echo esc_attr( $_POST['username'] ); ?>" />
</label>
</p>
<?php endif; ?>
<p class="form-row form-row-wide">
<label for="reg_email"><?php _e( 'Email address', 'workscout' ); ?> <span class="required">*</span>
<i class="ln ln-icon-Mail"></i><input type="email" class="input-text" name="email" id="reg_email" value="<?php if ( ! empty( $_POST['email'] ) ) echo esc_attr( $_POST['email'] ); ?>" />
</label>
</p>
<?php if ( 'no' === get_option( 'woocommerce_registration_generate_password' ) ) : ?>
<p class="form-row form-row-wide">
<label for="reg_password"><?php _e( 'Password', 'workscout' ); ?> <span class="required">*</span>
<i class="ln ln-icon-Lock-2"></i><input type="password" class="input-text" name="password" id="reg_password" />
</label>
</p>
<?php endif; ?>
<!-- Spam Trap -->
<div style="<?php echo ( ( is_rtl() ) ? 'right' : 'left' ); ?>: -999em; position: absolute;"><label for="trap"><?php _e( 'Anti-spam', 'workscout' ); ?></label><input type="text" name="email_2" id="trap" tabindex="-1" /></div>
<?php do_action( 'woocommerce_register_form' ); ?>
<?php do_action( 'register_form' ); ?>
<p class="form-row">
<?php wp_nonce_field( 'woocommerce-register' ); ?>
<input type="submit" class="button" name="register" value="<?php esc_attr_e( 'Register', 'workscout' ); ?>" />
</p>
<?php do_action( 'woocommerce_register_form_end' ); ?>
</form>
<?php } else {
_e('User registration is not enabled','workscout');
}
}
}
add_shortcode('workscout_register_form', 'workscout_registration_form');
I don't have much knowledge on php, I am little confused between the functions I have added here.
function wc_custom_user_redirect( $redirect, $user ) {
// Get the first of all the roles assigned to the user
$role = $user->roles[0];
$dashboard = admin_url();
$myaccount = get_permalink( wc_get_page_id( 'myaccount' ) );
if( $role == 'employer' ) {
if(get_option( 'job_manager_job_dashboard_page_id')) {
$redirect_to = get_permalink(get_option( 'job_manager_job_dashboard_page_id'));
} else {
$redirect_to= home_url();
};
} elseif ( $role == 'candidate' ) {
if(get_option( 'resume_manager_candidate_dashboard_page_id')) {
$redirect_to = get_permalink(get_option( 'resume_manager_candidate_dashboard_page_id'));
} else {
$redirect_to= home_url();
};
} elseif ( $role == 'customer' || $role == 'subscriber' ) {
//Redirect customers and subscribers to the "My Account" page
$redirect = $myaccount;
} else {
//Redirect any other role to the previous visited page or, if not available, to the home
$redirect = wp_get_referer() ? wp_get_referer() : home_url();
}
return $redirect;
}
add_filter( 'woocommerce_login_redirect', 'wc_custom_user_redirect', 10, 2 );
Do i have to added some redirect code in this function, I tried commenting and adding a redirection code, but it didn't work
if ( ! function_exists( 'workscout_add_new_member' ) ) :
function workscout_add_new_member() {
$login_system = Kirki::get_option( 'workscout', 'pp_login_form_system' );
if($login_system == 'workscout') {
if (isset( $_POST["workscout_register_check"] ) && wp_verify_nonce($_POST['workscout_register_nonce'], 'workscout-register-nonce')) {
if ( !isset($_POST['confirm_email']) || $_POST['confirm_email'] !== '' ) {
home_url( '/' );
exit;
}
$user_login = $_POST["workscout_user_login"];
$user_email = $_POST["workscout_user_email"];
$user_role = $_POST["workscout_user_role"];
if(username_exists($user_login)) {
// Username already registered
workscout_form_errors()->add('username_unavailable', __('Username already taken','workscout'));
}
if(!validate_username($user_login)) {
// invalid username
workscout_form_errors()->add('username_invalid', __('Invalid username','workscout'));
}
if($user_login == '') {
// empty username
workscout_form_errors()->add('username_empty', __('Please enter a username','workscout'));
}
if(!is_email($user_email)) {
//invalid email
workscout_form_errors()->add('email_invalid', __('Invalid email','workscout'));
}
if(email_exists($user_email)) {
//Email address already registered
workscout_form_errors()->add('email_used', __('Email already registered','workscout'));
}
$password = wp_generate_password();
$password_generated = true;
if(empty($user_role)) {
$user_role = 'candidate';
}
$errors = workscout_form_errors()->get_error_messages();
// only create the user in if there are no errors
if(empty($errors)) {
$new_user_id = wp_insert_user(array(
'user_login' => $user_login,
'user_pass' => $password,
'user_email' => $user_email,
'user_registered' => date('Y-m-d H:i:s'),
'role' => $user_role,
)
);
if($new_user_id) {
// send an email to the admin alerting them of the registration
//
if (function_exists('sb_we_init')) {
wp_new_user_notification( $new_user_id, null, 'both' );
} else {
workscout_wp_new_user_notification($new_user_id,$password);
}
// log the new user in
// $creds = array();
// $creds['user_login'] = $user_login;
// $creds['user_password'] = $password;
// $creds['remember'] = true;
// $user = wp_signon( $creds, false );
// send the newly created user to the home page after logging them in
if ( is_wp_error($user) ){
echo $user->get_error_message();
} else {
wp_safe_redirect( add_query_arg( 'success', 1, home_url( '/' ) ) );
}
exit;
}
}
}
}
}
endif;
add_action('init', 'workscout_add_new_member');
I found this additional code. Do you think home url should be added here ?
function workscout_ajax_register(){
check_ajax_referer( 'ajax-register-nonce', 'security' );
// Nonce is checked, get the POST data and sign user on
$info = array();
$info['user_login'] = sanitize_user($_POST['username']);
$info['user_email'] = sanitize_email( $_POST['email']);
$info['user_role'] = sanitize_email( $_POST['role']);
$valid = true;
if(username_exists( $info['user_login'])) {
// Username already registered
echo json_encode(array('loggedin'=>false, 'message'=>__('Username already taken','workscout'), 'type'=>"error notification " ));
$valid = false;
die();
}
if(!validate_username( $info['user_login'])) {
// invalid username
echo json_encode(array('loggedin'=>false, 'message'=>__('Invalid username','workscout'), 'type'=>"error notification " ));
$valid = false;
die();
}
if( $info['user_login'] == '') {
// empty username
echo json_encode(array('loggedin'=>false, 'message'=>__('Please enter a username','workscout'), 'type'=>"error notification " ));
$valid = false;
die();
}
if(!is_email($info['user_email'])) {
//invalid email
echo json_encode(array('loggedin'=>false, 'message'=>__('Invalid email','workscout'), 'type'=>"error notification " ));
$valid = false;
die();
}
if(email_exists($info['user_email'])) {
//Email address already registered
echo json_encode(array('loggedin'=>false, 'message'=>__('Email already registered','workscout'), 'type'=>"error notification " ));
$valid = false;
die();
}
$password = wp_generate_password();
$password_generated = true;
$info['user_pass'] = $password;
// Register the user
if($valid) {
$user_register = wp_insert_user( $info );
if ( is_wp_error($user_register) ){
$error = $user_register->get_error_codes() ;
if(in_array('empty_user_login', $error))
echo json_encode(array('loggedin'=>false, 'message'=>__($user_register->get_error_message('empty_user_login')), 'type'=>"error notification " ));
elseif(in_array('existing_user_login',$error))
echo json_encode(array('loggedin'=>false, 'message'=>__('This username is already registered.','workscout'), 'type'=>"error notification " ));
elseif(in_array('existing_user_email',$error))
echo json_encode(array('loggedin'=>false, 'message'=> __('This email address is already registered.','workscout'), 'type'=>"error notification " ));
} else {
if (function_exists('sb_we_init')) {
wp_new_user_notification( $user_register, null, 'both' );
} else {
workscout_wp_new_user_notification($user_register,$password);
}
$creds = array();
$creds['user_login'] = $info['user_login'];
$creds['user_password'] = $password;
$creds['remember'] = true;
$user_signon = wp_signon( $creds, false );
if ( is_wp_error($user_signon) ){
echo json_encode(array('loggedin'=>false, 'message'=>__('Wrong username or password.','workscout'), 'type'=>"error notification " ));
} else {
wp_set_current_user($user_signon->ID);
$oUser = get_user_by( 'login', $creds['user_login'] );
$aUser = get_object_vars( $oUser );
$sRole = $aUser['roles'][0];
echo json_encode(array('loggedin'=>true, 'message'=>__('Registration successful, redirecting...','workscout'), 'type'=>'success notification ', 'role'=> $sRole ));
}
}
}
die();
}
endif;
?>
Try this code
add_filter( 'registration_redirect', 'my_redirect_home' );
function my_redirect_home( $registration_redirect ) {
return home_url();
}
Please add code like below n check might be it works.
Please try it for both position by uncommenting.
<form>
<p class="form-row">
<?php wp_nonce_field( 'woocommerce-register' ); ?>
<input type="submit" class="button" name="register" value="<?php esc_attr_e( 'Register', 'workscout' ); ?>" />
//<?php wp_redirect( home_url() );?>
</p>
<?php do_action( 'woocommerce_register_form_end' ); ?>
</form>
//<?php wp_redirect( home_url() ); ?>

Custom Contact Form with simple Math Captcha

I have a well working contact form on my site. Now I'm trying to include a math captcha to the from. Unfortunately, I was not able to make it work. Any idea how (where) to include the captcha codes?
I tried a lot of things, but it does not work properly. Maybe the code is not the best :) I already searched for a solution in stackoverflow and google with no luck.
My working contact form at the moment:
<?php
if(isset($_POST['submitted'])) {
if(trim($_POST['contactName']) === '') {
$nameError = sprintf( __( 'Please enter your name.', 'test_theme' ) );
$hasError = true;
} else {
$name = trim($_POST['contactName']);
}
if(trim($_POST['email']) === '') {
$emailError = sprintf( __( 'Please enter your email address.', 'test_theme' ) );
$hasError = true;
} else if (!preg_match("/^[[:alnum:]][a-z0-9_.-]*#[a-z0-9.-]+\.[a-z]{2,4}$/i", trim($_POST['email']))) {
$emailError = sprintf( __( 'You entered an invalid email address.', 'test_theme' ) );
$hasError = true;
} else {
$email = trim($_POST['email']);
}
if(trim($_POST['comments']) === '') {
$commentError = sprintf( __( 'Please enter a message.', 'test_theme' ) );
$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 = sprintf( __( 'Contact Form', 'test_theme' ) );
$body = "Name: $name \n\nMail: $email \n\n $comments";
$headers = 'From: '.$name.' <'.$emailTo.'>' . "\r\n" . 'Reply-To: ' . $email;
wp_mail($emailTo, $subject, $body, $headers);
$emailSent = true;
}
} ?>
<?php if(isset($emailSent) && $emailSent == true) { ?>
<div class="thanks">
<p><?php _e( 'Thanks, your email was sent successfully.', 'test_theme' ); ?></p>
</div>
<?php } else { ?>
<?php if(isset($hasError) || isset($captchaError)) { ?>
<p class="error-conform"><?php _e( 'Sorry, an error occured.', 'test_theme' ); ?><p>
<?php } ?>
<form action="<?php the_permalink(); ?>" class="author-description" id="contactForm" method="post">
<h2><?php _e( 'Contact Us', 'test_theme' ); ?></h2><br />
<p><label for="contactName"><?php _e( 'Your Name', 'test_theme' ); ?> <span>*</span>
<?php if($nameError != '') { ?>
<span class="error-conform"><?=$nameError;?></span>
<?php } ?><br />
<input type="text" name="contactName" id="contactName" value="<?php if(isset($_POST['contactName'])) echo $_POST['contactName'];?>" /></label></p>
<p><label for="email"><?php _e( 'Your Email Adress', 'test_theme' ); ?> <span>*</span>
<?php if($emailError != '') { ?>
<span class="error-conform"><?=$emailError;?></span>
<?php } ?><br />
<input type="text" name="email" id="email" value="<?php if(isset($_POST['email'])) echo $_POST['email'];?>" /></label></p>
<p><label for="commentsText"><?php _e( 'Your Message', 'test_theme' ); ?> <span>*</span>
<?php if($commentError != '') { ?>
<span class="error-conform"><?=$commentError;?></span>
<?php } ?><br />
<textarea type="text" name="comments" id="commentsText" rows="20" cols="30"><?php if(isset($_POST['comments'])) { if(function_exists('stripslashes')) { echo stripslashes($_POST['comments']); } else { echo $_POST['comments']; } } ?></textarea></label></p>
<p><input type="submit"></p>
<input type="hidden" name="submitted" id="submitted" value="true" />
</form>
<?php } ?>
Captcha Code that should included in the contact form above:
Part 1:
if(!isset($_POST['submitted'])) {
session_start();
$digit1 = mt_rand(1,6);
$digit2 = mt_rand(1,6);
$math = "$digit1 + $digit2";
$_SESSION['answer'] = $digit1 + $digit2;
}
Part 2:
if ($_SESSION['answer'] != $_POST['answer'] ) {
$mathError = 'Please answer the math question.';
$hasError = true;
}
Part 3:
<span class="error-conform"><?=$mathError;?></span>
<li><label>What's <?php echo $math; ?> = </label><input name="answer" type="text" /></li>
I guess this will give you some ideas.
<?php
session_start(); // session start should be the very first line of your php code, for session management
// checking whether the form is being submitted by the user
if( isset($_POST['submitted']) )
{
// checking whether the user submitted answer matches with the captcha
if ($_SESSION['answer'] != $_POST['answer'] )
{
$mathError = 'Please answer the math question.';
$hasError = true;
}
// ....
// do other form validations here..
// ....
if( !$hasError )
{
// no errors, so send the mail or do whatever you want to do here...
}
}
// now generating new captcha
$digit1 = mt_rand(1,6);
$digit2 = mt_rand(1,6);
$math = "$digit1 + $digit2";
$_SESSION['answer'] = $digit1 + $digit2;
?>
<!-- html goes here --->
<forma ction="<?php the_permalink(); ?>
<!-- include the form fields here... -->
<?php if(!empty($mathError)) { ?>
<span class="error-conform"><?php echo $mathError; ?></span>
<?php } ?>
<label>What's <?php echo $math; ?> = </label><input name="answer" type="text" />
<input type="hidden" name="submitted" id="submitted" value="true" />
</form>
<!-- rest of the html goes here --->

Categories