Prefill the comment form in WordPress

I’m pretty sure I’m not the only one who hate filling out name, email and homepage every time I leave a comment. Many sites ‘solve’ this by pulling in Disqus, but they don’t allow custom CSS. And I think it’s a bit of an overkill; after all, we’re just going to store three fields of information.

So, I came up with an alternative solution:  Instead of storing the data on the server, why not do it right in the browser? The script below saves user data in the browser’s local storage whenever the form changes, and fills the form automatically when the user loads a new page. In case the user leaves the page without posting the comment, the text will be saved. Then, the user can come back later, and the draft will be there.

Using it is really simple: just copy and paste the code below into your theme’s javascript file. Feel free to use (and modify) the script for whatever you want.

// WP comment form pre-fill by Simen.codes (http://simen.codes)
( function( $ ) {
	if (localStorage && $('#comments').length > 0) {
		if (localStorage.comments_email) {
			$('#comments .comment-form-author input').val(localStorage.comments_author);
			$('#comments .comment-form-email input').val(localStorage.comments_email);
			$('#comments .comment-form-url input').val(localStorage.comments_url);
			if ($('article.post').attr('id') == localStorage.comments_commentid) {
				$('#comments .comment-form-comment textarea').val(localStorage.comments_comment);
			}
		}

		$('#comments .comment-form input, #comments .comment-form textarea').change(function(event) {
			$target = $(event.target);
			switch ($target.attr('name')) {
				case 'author':
					localStorage.comments_author = $target.val();
					break;
				case 'email':
					localStorage.comments_email = $target.val();
					break;
				case 'url':
					localStorage.comments_url = $target.val();
					break;
				case 'comment':
					localStorage.comments_comment = $target.val();
					localStorage.comments_commentid = $('article.post').attr('id');
					break;
			}
		});
	}
} )( jQuery );

If you want to try it, use the form below. (Note: comments submitted here won’t be published)

Edit: I thought it was obvious, but this is not the place to ask for help with Heads-up. I do not answer questions posted here.

Leave a Reply

Your email address won't be published. Required fields are marked *