CF7: Redirect to another URL if submission error - wordpress

I have created a form using the Contact Form 7 plugin for WordPress.
My form looks like this:
<label> User Name*
[text* your-name] </label>
<label> Email Adress*
[email* your-email] </label>
[submit "Register"]
I can detect if someone trying to use the same email address (already registered) via this tutorial, https://cfdbplugin.com/?page_id=904
But, WHILE showing the error message, how can I let the page redirect him to another URL after some amount of time? For example to "/homesite/?para="
Maybe I need to do something with this code
if (is_already_submitted($formName, $fieldName, $_POST[$name])) {
$result->invalidate($tag, $errorMessage);
}
}
return $result;
But I don't know how should I amend those code. Please help me.

You can do this using DOM Events. CF7 has custom DOM events, which can be used to redirect users to other page. Since you want to redirect when form data is invalid, you will need to use wpcf7invalid event.
wpcf7invalid — Fires when an Ajax form submission has completed successfully, but mail hasn’t been sent because there are fields with invalid input.
A quick example:
function my_awesome_cf7_custom_events () { ?>
<script type="text/javascript">
document.addEventListener( 'wpcf7invalid', function( event ) {
if ( 'FORM_ID' == event.detail.contactFormId ) {//<===replace FORM_ID with form id
location.replace('https://your-new-url/');
}
}, false );
</script>
<?php }
add_action( 'wp_footer', 'my_awesome_cf7_custom_events' );
Replace FORM_ID with your form id, and set your url.
More about CF7 DOM events

Related

How can i connect custom HTML form with wordpress email adress

I am using Wordpress and framework Gantry 5, I have custom html form added via JS as an innerHTML added to existing container.
I want this form values be submitted to email adress defined in WordPress administration settings. Is there any way i can achieve it?
it depends from the form action, if your form action call a function inside your wordpress (for example in function.php) you can pick the email address
get_option('admin_email')
and use it to send the post data.
If the form action call a function external to you wordpress you can add the email as an hidden field in your form
<input type="hidden" id="email" name="email" value="<?php echo get_option('admin_email'); ?>">
and get the value in the $_POST object.
Because you form is added by javascript you can add the hidden field by javascript before the form submit maybe using jquery (you also can do this in vanilla js).
If you print the script directly inline with php
$("#yourFormID").submit( function(eventObj) {
$("<input />").attr("type", "hidden")
.attr("name", "email")
.attr("value", "<?php echo get_option('admin_email'); ?>" )
.appendTo("#form");
return true;
});
If you put the script in js file you can print the hidden field outside with php and then pick the value with jquery (or also vanilla)
<input type="hidden" id="email" name="email" value="<?php echo get_option('admin_email'); ?>">
$("#yourFormID").submit( function(eventObj) {
$("<input />").attr("type", "hidden")
.attr("name", "email")
.attr("value", $('#email').val() )
.appendTo("#form");
return true;
});

Contact Form 7: how to target only one submit button

I have a contact form 7 form which upon submission should redirect the user to the applicable page. I have three submit buttons and each should redirect to different pages. I can't figure out how to set up different redirections for the submit buttons. Anyone can help with that?
Here is my form:
<div class="popup-form" style="text-align:center; margin-bottom:0.5rem;">To be able to see the packages, please fill in the below form.</div>
<div class="popup-form">
<label> Name: <span class="required">*</span>
[text* your-name class:with-border]</label></div>
<div class="popup-form">
<label> Email: <span class="required">*</span>
[email* your-email class:with-border] </label></div>
<div class="popup-form">
<label> Company: <span class="required">*</span>
[text* Company class:with-border] </label></div>
<div class="popup-form">
<label> Phone: <span class="required">*</span>
[tel* Phone class:with-border] </label></div>
[acceptance GDPR class:popup-form] I understand and accept the privacy policy [/acceptance]
<p class="submit-button popup-form"><span class="english">[submit class:english-submit "English"]</span> [submit "Italian"][submit "Spanish"]</p>
And this is the redirection code in my header.php. At the moment it redirects no matter which submit button I click on.
document.addEventListener( 'wpcf7submit', function( event ) {
if ( '352' == event.detail.contactFormId )
{
location = 'http://example1.com';
}
}, false );
Thank you!
How about you try and give different class names to your initial labels? This will allow you to manipulate the buttons using their ID or Class name. At the moment, you are using the same class name for all your labels.
You can't. wpcf7submit event is an event that is called when form gets submitted. It can be caused by pushing a button, but also by pressing enter key.
So this event is not directly attached to any button so you can't access that button.
One way to solve this is to add custom event handlers for button clicks and set make them set value of some hidden input inside the form. This way that value will be sent with the form data.
Thank you very much for your help guys. Unfortunately none of the above worked for me.
However I managed to find a way to make it work, I added this in header.php:
<script>
window.onload=function(){
var englishSubmit = document.getElementsByClassName("english-submit");
englishSubmit[0].addEventListener("click", function()
{
window.location.href = "/packages-en/";
});
var italianSubmit = document.getElementsByClassName("italian-submit");
italianSubmit[0].addEventListener("click", function()
{
window.location.href = "/packages-it/";
});
var spanishSubmit = document.getElementsByClassName("spanish-submit ");
spanishSubmit[0].addEventListener("click", function()
{
window.location.href = "/packages-sp/";
});
}
</script>

Activate link upon reCAPTCHA success?

I'm working on a WordPress site. Basically, I publish download links (PDFs), and would like to stop web crawlers from accessing this content. This led me to Google's reCAPTCHA. Can I use this alone, so that when a user clicks/answers correctly, the links on the page will be made active? I'm having trouble editing a page in WordPress to do this. Thanks.
-Rudy.
I understand that you want to show link dynamically after the verification of the recaptcha.
You can create a an ajax that fetches the link after the verifcation of recaptcha passes.
To do this, we will use WordPress ajax requests, wp-ajax:
First, you register the ajax handler the request in the server side
add_action( 'wp_ajax_get_hidden_pdf_link', 'search_hidden_pdf_link' );
// add this line to handle requests of non logged in users
add_action( 'wp_ajax_nopriv_get_hidden_pdf_link', 'search_hidden_pdf_link' );
function search_hidden_pdf_link() {
// the response will be ajax response
header('Content-Type: application/json;charset=utf-8');
if(recaptcha_fails()){
// writing the failure response
echo json_encode(array('object' => 'error'));
wp_die();
}
$secret_pdf_link = generate_pdf_link();
// writing the succcess response
echo( json_encode( array('object' => 'success', 'link' => $secret_pdf_link)));
wp_die();
}
and in the front end, you create an ajax form, which asks and displays the link.
PDF Link
<form id="pdf-link-form" action="<?php echo admin_url('wp-ajax.php'); ?>">
<!-- some input that tells the backend which pdf to fetch -->
<input type="hidden" name="public_pdf_id" value="<?php echo $pdf_id; ?>">
<!-- the ajax request identifier, it is the suffix inside the action -->
<input type="hidden" name="action" value="get_hidden_pdf_link">
<div class="g-recaptcha" data-sitekey="your_site_key"></div>
</form>
<script>
$(document).ready(function () {
$('#pdf-link-form').submit(function (event) {
event.preventDefault();
form = $(this);
$.ajax({
type: 'POST',
url: form.attr('action'),
data: form.serializeArray()
}).done(function (result) {
if(result.object == 'success'){
$('#hidden-pdf-link').attr('href', result.link);
form.remove();
alert('you can access the pdf')
} else {
alert('you are not allowed to access my pdf!!');
}
})
});
});
</script>

Theme my login validate profile page?

I am using the theme my login WordPress plugin, using the custom pages I have added my own registration fields and validated them with no issues.
However I have worryingly discovered that corrupt code can be added and update to the profile page once a user is registered, I am wondering if there is the same offering for the profile page in terms of validation as there is for the registration?
The best way would be to use "theme my login" template pages, it already have the registration and profile part. You can add and remove fields to your liking and also style it, here is a tutorial for that
http://www.jfarthing.com/development/theme-my-login/adding-extra-registration-fields/.
If you have your custom built profile page then i suggest you use wpnonce to check the validity of the POST requests. Secondly use wordpress's own functions for fetching and updating data. Functions like get_user_meta and update_user_meta, these come built in with all the validation and you dont have to worry about it.
EDIT : I have written this code to demonstrate how to use a nonce field and then how to check the validity of the nonce field (By default Nonces are valid for 24 hours). The code below adds a form and asks for users height. The first php part wont run until the post request has been made. Once the request has been made then it checks for the integrity of the request. If all conditions are met then it will add a new meta field in the database called 'user_height', and will be updated every time the user changes it. Once the height has been set, it will also auto populate this in the input box, so they can see what is their current height. I hope this code covers all your doubts of showing user meta, adding/updating user meta and also validation nonces.
<?php
// Checking if the post request has been submitted and then verifing nonce
if (!isset( $_POST['get_user_height'] ) || !wp_verify_nonce( $_POST['get_user_height'], 'user_body_built' )
) {
print 'Sorry, the request cannot be verified.';
exit;
} else {
if(isset($_POST['user_height']) && !empty($_POST['user_height'])){
update_user_meta( $user_id, 'user_height', $_POST['user_height']);
}
}
<form method="post">
// Fetching previous height of user
<?php $user_height = get_user_meta($user_id, 'user_height', TRUE);?>
// Getting user's height and then saving it to users meta, if height was already set it will also show the current height.
<input type="text" name="user_height" <?php if($user_height){echo 'value="'.$user_height.'"';} ?> placeholder="enter your height">
// Generating a nonce field which will be checked on post request
<?php wp_nonce_field( 'user_body_built', 'get_user_height' ); ?>
</form>
Second EDIT (showcasing how to use existing registration fields on profile page, replace input names with the ones on registeration page): Just add this code in your profile page or functions.php it will automatically show these fields in the profile page.
function tml_edit_user_profile( $profileuser ) {?>
<p>
<label for="phone_number">Phone Number</label>
<!-- replace name attribute with the ones used on registration page -->
<input id="phone_number" type="text" name="phone_number" value="<?php echo $profileuser->phone_number; ?>" />
</p>
<?php
}
add_action( 'edit_user_profile', 'tml_edit_user_profile' );

How to add CSRF to manually created form in wordpress?

This is my first try to writing custom plugin in WordPress, Certainly there is a way to add CSRF tag to forms in WordPress and check form validity inside server. The question is how can I?
If you are using Wordpress 2.0.4 or above you can use wp_nonce_field and wp_verify_nonce field to verify. The Wordpress documentation has some examples (which I posted below).
In your form:
<form method="post">
<!-- some inputs here ... -->
<?php wp_nonce_field('name_of_my_action','name_of_nonce_field'); ?>
</form>
In your processing action:
<?php
if ( empty($_POST) || !wp_verify_nonce($_POST['name_of_nonce_field'],'name_of_my_action') )
{
print 'Sorry, your nonce did not verify.';
exit;
}
else
{
// process form data
}

Resources