Skip to content

Instantly share code, notes, and snippets.

@fedek6
Created March 13, 2018 09:56
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
  • Save fedek6/0a0e79a97b49664354d76b8b3c4ccc6d to your computer and use it in GitHub Desktop.
Save fedek6/0a0e79a97b49664354d76b8b3c4ccc6d to your computer and use it in GitHub Desktop.
Ajax support for WP Newsletter plugin (https://www.thenewsletterplugin.com)
<?php
/** @constant string THEME_NAME **/
define( 'THEME_NAME', get_option('stylesheet') );
/**
* Custom script
*/
function my_scripts_method() {
wp_enqueue_script(
'custom-script',
get_stylesheet_directory_uri() . '/js/main.js',
array( 'jquery' ),
'1.2'
);
if ( !is_admin() ) {
/** */
wp_localize_script( 'custom-script', 'ajax', array(
'url' => admin_url( 'admin-ajax.php' ),
'ajax_nonce' => wp_create_nonce( 'noncy_nonce' ),
'assets_url' => get_stylesheet_directory_uri(),
) );
}
}
add_action( 'wp_enqueue_scripts', 'my_scripts_method' );
/**
* Ajax newsletter
*
* @url http://www.thenewsletterplugin.com/forums/topic/ajax-subscription
*/
function realhero_ajax_subscribe() {
check_ajax_referer( 'noncy_nonce', 'nonce' );
$data = urldecode( $_POST['data'] );
if ( !empty( $data ) ) :
$data_array = explode( "&", $data );
$fields = [];
foreach ( $data_array as $array ) :
$array = explode( "=", $array );
$fields[ $array[0] ] = $array[1];
endforeach;
endif;
if ( !empty( $fields ) ) :
global $wpdb;
// check if already exists
/** @var int $count **/
$count = $wpdb->get_var( $wpdb->prepare("SELECT COUNT(*) FROM {$wpdb->prefix}newsletter WHERE email = %s", $fields['ne'] ) );
if( $count > 0 ) {
$output = array(
'status' => 'error',
'msg' => __( 'Already in a database.', THEME_NAME )
);
} elseif( !defined( 'NEWSLETTER_VERSION' ) ) {
$output = array(
'status' => 'error',
'msg' => __( 'Please install & activate newsletter plugin.', THEME_NAME )
);
} else {
/**
* Generate token
*/
/** @var string $token */
$token = wp_generate_password( rand( 10, 50 ), false );
$wpdb->insert( $wpdb->prefix . 'newsletter', array(
'email' => $fields['ne'],
'status' => $fields['na'],
'http_referer' => $fields['nhr'],
'token' => $token,
)
);
$opts = get_option('newsletter');
$opt_in = (int) $opts['noconfirmation'];
// This means that double opt in is enabled
// so we need to send activation e-mail
if ($opt_in == 0) {
$newsletter = Newsletter::instance();
$user = NewsletterUsers::instance()->get_user( $wpdb->insert_id );
NewsletterSubscription::instance()->mail($user->email, $newsletter->replace($opts['confirmation_subject'], $user), $newsletter->replace($opts['confirmation_message'], $user));
}
$output = array(
'status' => 'success',
'msg' => __( 'Thank you!', THEME_NAME )
);
}
else :
$output = array(
'status' => 'error',
'msg' => __( 'An Error occurred. Please try again later.', THEME_NAME )
);
endif;
wp_send_json( $output );
}
add_action( 'wp_ajax_realhero_subscribe', 'realhero_ajax_subscribe' );
add_action( 'wp_ajax_nopriv_realhero_subscribe', 'realhero_ajax_subscribe' );
function validateEmail(email) {
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,}))$/;
return re.test(email);
};
jQuery(function($){
// now you can use jQuery code here with $ shortcut formatting
// this executes immediately - before the page finishes loading
/**
* Newsletter support
*/
$('#newsletter')
.attr('novalidate', true)
.each( function() {
var $this = $(this),
$input = $this.find( 'input[name="ne"]'),
$noti = $input.prev(),
$submit = $this.find( 'input[type="submit"]'),
showNoti = function(txt) {
var $msg = $noti.clone();
$noti.before($msg);
$noti.remove();
$msg.text( txt ).addClass('vaporize').attr('aria-hidden', 'false');
},
success = function() {
$this
.fadeOut('slow', function() {
$this.replaceWith( '<p class="appear-nicely dynamic-msg">Thank you!</p>' );
});
};
// Submit handler
$this.submit( function(e) {
var serializedData = $this.serialize();
$noti = $input.prev();
console.log( 'INFO: Form submit.' );
e.preventDefault();
// validate
if( validateEmail( $input.val() ) ) {
var data = {};
// Prepare ajax data
data = {
action: 'realhero_subscribe',
nonce: ajax.ajax_nonce,
data: serializedData
}
// send ajax request
$.ajax({
method: "POST",
url: ajax.url,
data: data,
beforeSend: function() {
$input.prop( 'disabled', true );
$submit.val('Wait').prop( 'disabled', true );
},
success: function( data ) {
if( data.status == 'success' ) {
success();
console.log( 'INFO: OK!' );
} else {
$input.prop( 'disabled', false );
$submit.val('Submit').prop( 'disabled', false );
showNoti( data.msg );
console.log( 'INFO: Bad response.' );
}
}
});
console.log( 'INFO: Email ok.' );
} else {
showNoti( 'Enter valid e-mail address!' );
};
});
});
});
<aside id="newsletter-form">
<div>
<h1 class="widget-title">Newsletter</h1>
<div class="widget">
<p>Be upddated!</p>
</div><!--
--><div class="widget">
<form id="newsletter" role="form" method="get" class="search-form" action="http://domain.com/">
<label>
<span class="screen-reader-text">E-mail:</span>
<span class="notification" aria-hidden="true"></span>
<input class="email-field" placeholder="Type your e-mail" value="" name="ne" type="email">
</label>
<input type="hidden" name="na" value="S">
<input type="hidden" name="nhr" value="<?php echo get_bloginfo( 'url' ) ?>">
<input class="email-submit" value="Submit" type="submit">
</form>
</div>
</div>
</aside><!-- #newsletter-form -->
/**
* Newsletter form
*/
@keyframes appear-nicely {
0% {
opacity: 0;
}
100% {
opacity: 1;
}
}
.appear-nicely {
animation: appear-nicely 2s forwards ease-out;
}
#wolontariat #newsletter-form {
background-color: #24282d;
padding: 32px 40px;
margin-left: -40px;
box-sizing: content-box;
width: 100%;
color: White;
text-align: center;
position: relative;
}
#wolontariat #newsletter-form > div {
max-width: 1000px;
margin: 0 auto;
}
#wolontariat #newsletter-form h1 {
color: White;
}
#wolontariat #newsletter-form .widget {
float: none;
width: 100%;
display: inline-block;
margin: 0 0;
padding: 16px;
box-sizing: border-box;
vertical-align: middle;
}
#wolontariat #newsletter-form .widget p img {
vertical-align: middle;
}
#wolontariat #newsletter-form .widget .disclaimer {
padding: 0 0;
margin: 10px 0 0 0;
font-size: .625rem;
}
#wolontariat #newsletter-form .email-submit {
min-width: 100%;
margin-top: 16px;
}
@keyframes vaporize {
0% {
opacity: 1;
}
100% {
opacity: 0;
top: -80px;
}
}
#wolontariat #newsletter-form .notification[aria-hidden="true"] {
display: none;
}
#wolontariat #newsletter-form .notification[aria-hidden="false"] {
display: block;
position: absolute;
top: -25px;
left: 0px;
}
.vaporize {
animation: vaporize 1.5s forwards ease-out;
}
@adsim
Copy link

adsim commented Oct 8, 2020

Thanks for your code and your work. Very useful.
You have a little error in your functions.php.
In the line NewsletterSubscription::instance()->mail($user->email, $newsletter->replace($opts['confirmation_subject'], $user), $newsletter->replace($opts['confirmation_message'], $user)); $user->email is wrong. The mail function of NewsletterSubscription needs the user as first parameter, not the email. So it must be NewsletterSubscription::instance()->mail($user, $newsletter->replace($opts['confirmation_subject'], $user), $newsletter->replace($opts['confirmation_message'], $user));

@thr4sher
Copy link

thr4sher commented Oct 9, 2020

Thank you very much fedek6.

@fedek6
Copy link
Author

fedek6 commented Oct 30, 2020

Thanks for your code and your work. Very useful.
You have a little error in your functions.php.
In the line NewsletterSubscription::instance()->mail($user->email, $newsletter->replace($opts['confirmation_subject'], $user), $newsletter->replace($opts['confirmation_message'], $user)); $user->email is wrong. The mail function of NewsletterSubscription needs the user as first parameter, not the email. So it must be NewsletterSubscription::instance()->mail($user, $newsletter->replace($opts['confirmation_subject'], $user), $newsletter->replace($opts['confirmation_message'], $user));

Hey! Thanks for this addition. This is a very old gist, it's not maintained anymore. I hope your comment will guide anyone with problems :)

@adsim
Copy link

adsim commented Oct 30, 2020

Yeah, I thought it was old, but nevertheless it works (with this little modification) and is very useful.

@rloes
Copy link

rloes commented Mar 6, 2023

Very useful, but the current code does not send the confirmation mail for me. According to the github repo of thenewsletterplugin I replaced line 90 of function.php:
NewsletterSubscription::instance()->mail($user->email, $newsletter->replace($opts['confirmation_subject'], $user),
with:
NewsletterSubscription::instance()->send_message('confirmation', $user, true);

I hope this helps anyone facing the same problem.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment