This is a quick post, just to share something I learned.
Recently I got a request to create a simple submit form with a an email input that would direct to another page and take the email address and pre-fill a more complex form with email, name, address, etc.
Below is the code I used for it.
[php]
<?php
/**
* Create a simple shortcode for a newsletter CTA
* Load JS conditionally, only if the page is ‘newsletter’
*/
add_action( ‘wp’, ‘n8f_load_rr_signup_cta_scripts_on_newsletter_page’);
function n8f_load_rr_signup_cta_scripts_on_newsletter_page() {
if( is_page(‘newsletter’) ) {
add_action( ‘wp_enqueue_scripts’, ‘register_n8f_rr_signup_cta_scripts’ );
}
}
function register_n8f_rr_signup_cta_scripts() {
wp_enqueue_script( ‘n8f_rr_signup_cta_js’, get_stylesheet_directory_uri() . ‘/js/newsletter_signup_cta.js’, array( ‘jquery’ ), date("ymd"), true);
}
add_shortcode( ‘n8f_rr_signup_cta’, ‘n8f_rr_signup_cta’ );
function n8f_rr_signup_cta() {
$html = ‘<form action="/newsletter">
<input type="text" name="email" placeholder="Your email…" />
<input type="submit" value="Subscribe"/>
</form>’;
return $html;
}
[/php]
[js]
/**
* Parse the url for an email address
*/
(function($) {
$(document).ready(function() {
var queryString = location.search
queryStart = queryString.indexOf("=") + 1,
query = queryString.slice(queryStart, queryString.length ),
cleanString = query.replace( /%40/, "@");
$(‘#control_EMAIL’).val(cleanString);
});
})(jQuery);
[/js]