Samuel Elh Blog

WordPress, bbPress, BuddyPress, JavaScript tutorials and snippets

Tag: javascript

An effective way of preventing spam registration with JavaScript – WordPress

As I am writing this blog post about preventing spam registration on wordPress, many weblogs out there are getting tons of new accounts registered which belong to robots and are totally untolerated spam.

Preventing Spam Registration on WordPress

There are so many ways out there, free and paid, which would help you knock off spam registration on your WordPress blog or website. One of them is CleanTalk, I love this one as it has a great database of malware checks (blacklist) and many online ready tools to verify a user before it successfully signs up.

But for me, I always prefer not to add another plugin to the load, so if it was to coding a little snippet of script that would help then that would be super. So hopefully this could help out preventing spam registration somehow.

Preventing Spam Registration – JavaScript

As many of you know, or as if you don’t know, spam bots (robots) actually run microsystems that do not have JavaScript running. This means that no DOM JavaScript is available for bots, so we will use this point to add a required (but hidden) field into the user registration form that will work with WordPress nonces too (cool, right?) which will be verified with wp_verify_nonce() function..

Every time the registration screen is requested, the form field for spam check will be added on window load, and it will be required to process the registration.

Important notice – if you are on an environment where your users prefer not to enable JavaScript, then do not use this process OR, notify your users to enable JavaScript in order to register and then switch back to disabled JS mode.

Once the field was not added, the request will be killed with a simple error message:

WordPress are you spamming go back - preventing spam registration

Are you spamming?

Or possibly if you don’t want to kill the request but show a warning message notice instead, comment out wp_die function and remove the comments for $errors->add method usage in the script code; inside se_nospam_register_validate callback function, and this would appear:

bad guy spotted spam registration wordpress - preventing spam registration

Cool! now where can I get the plugin? (no plugin, just some small snippet of non commented code) ; read on.

Preventing Spam Registration on WordPress: The code

You can use the following code to be added to your child theme’s functions file, or download the plugin from Github gist:

<?php
/**
  * Plugin Name: No Spam Registration with JavaScript
  * Plugin URI:  http://blog.samelh.com
  * Description: Prevents spam registration on your WordPress blog/website by adding a necessary form field with JavaScript on document load
  * Author:      Samuel Elh
  * Author URI:  http://samelh.com
  * Version:     0.1
  */
add_action('register_form', 'se_nospam_register_append_input');
add_action('register_post', 'se_nospam_register_validate', 10, 3);
if ( !function_exists('se_nospam_register_append_input') ) :;
function se_nospam_register_append_input()
{
?>
	<script type="text/javascript" id="se_nospam_inline_js">
		window.onload = function() { // it's all about this JS, once JS is loaded, the spamcheck field will be available..
			var e = document.getElementById('se_nospam_inline_js');
			if ( null !== e ) {
				e.outerHTML = '<input id="process-register" type="hidden" name="process-register" value="<?php echo wp_create_nonce( 'se-nospam-register' ); ?>" />';
			} return;
		}
	</script>
<?php
}
endif;
if ( !function_exists('se_nospam_register_validate') ) :;
function se_nospam_register_validate( $login, $email, $errors )
{
	$die_message = apply_filters( "se_nospam_register_error", "Are you spamming?<br/><br/> <a href=\"javascript: window.history.go(-1);\">&laquo; Go back</a>" );
    if( !isset($_POST['process-register']) ) {
    	wp_die( $die_message );
        // or just: $errors->add( 'empty_realname', "<strong>ERROR</strong>: Are you spamming?" );
    }
    else if( empty($_POST['process-register']) )
    {
    	wp_die( $die_message );
        // or just: $errors->add( 'empty_realname', "<strong>ERROR</strong>: Are you spamming?" );
    }
    else if(!wp_verify_nonce($_POST['process-register'], 'se-nospam-register'))
    {
    	wp_die( $die_message );
        // or just: $errors->add( 'empty_realname', "<strong>ERROR</strong>: Are you spamming?" );
    }
    return $errors;
}
endif;

Cool! if preventing spam registration on WordPress with this custom trick has worked for you, then that’s what matters! Yay!! Personally it helped me a lot on my product support forums website where I have bbPress installed for the forums functionality.

Preventing Spam Registration on WordPress: After

Saying that it was helpful to preventing spam registration, there should be more to do after this, right? I mean like, capturing the prevented spam registration attempts and saving some count to the database so you can see a log of how many spam bots were blocked; something like adding this code:

update_option( $name = "se_how_many_spam", ( (int) get_option( $name ) ) + 1 );

That to be added right before each wp_die in the code, And then calling

get_option( "se_how_many_spam" );

to tell how much spam was denied. Also you might want to capture the user IP to block them or something, as long as possible, saying that spam can never be tolerated. (beware, bots will call you agressive then)

Note that this can also be effective on embedded forms like registration forms added with widgets or shortcodes, as the form field for spam check will be added with JavaScript there too.

That is it for this tutorial and I am hoping this helps you as it helped me and if there is any improvements or suggestions and ideas to implement, please feel free to discuss in below comments.

Thank you!

How to remove unwanted hash or other characters from WordPress page URL

WordPress: How to remove unwanted hash or other characters from WordPress page URL

In this quick tutorial, we will learn how to remove unwanted hashes, special characters, query variable parameters or any other type of text, from your WordPress page URL.

Remember that hashes are often added for a good reason, such as when switching tabs with JavaScript or when jumping from a section of the view-port to another through elements id attributes.. But if you really want to remove that, or you have specific character you want to eliminate, then, keep reading.

Now, you’ll have to think, whether this unwanted character is being placed on page load, or frequently after the page is loaded.

On page load:

Just add the following snippet to the bottom of your child theme functions file, or using a custom plugin. But, remember the add the targeted character within the variable inside the function:

$target = '#hash';

(for this, it will remove everything following #hash in the page url. Make it a hash (#stuff), or a query variable (?query=) or whatever fits your needs.

 

This is the code:

// replace #hash with your target character
add_action('wp_footer', function() {
	$target = '#hash';
	?>
		<script type="text/javascript">
		window.onload = function() {
		    var pageurl = window.location.href;
		    if( pageurl.indexOf('<?php echo $target; ?>') > 0 ) {
				var flush = pageurl.substring(0, pageurl.indexOf('<?php echo $target; ?>'));				
				window.history.replaceState( null, null, flush );
			}
		}
		</script>
	<?php
});

Frequently after page load:

For this one, we’ll set an interval to do the function repeatedly in order to verify whether our page URL is clean or not, from those unwanted characters:

// replace #hash with your target character, and $interval with number of milliseconds (1s = 1000 ms)
add_action('wp_footer', function() {
	$target = '#hash';
	$interval = '400';
	?>
		<script type="text/javascript">
		window.onload = function() {
			window.setInterval(function () {
			    var pageurl = window.location.href;
			    if( pageurl.indexOf('<?php echo $target; ?>') > 0 ) {
					var flush = pageurl.substring(0, pageurl.indexOf('<?php echo $target; ?>'));				
					window.history.replaceState( null, null, flush );
				}
			}, <?php echo $interval; ?>);
		}
		</script>
	<?php
});

© 2017 Samuel Elh - Powered by WordPress, DigitalOcean & NameCheap

Theme by Anders NorenUp ↑

Subscribe to our mailing list

Sign up to receive updates about WordPress, free and premium plugins and themes in general and tips and tricks

* indicates required