Past username in comment field & quote text

You have probably seen this function on different message boards. It allows to simple paste the comment author username in comment textarea and qoute some text from his/her comment with one click. I think it’s quite necessary feature. It will make commenting process more comfortable and encourages your users to comment on your posts.

Let’s start:

1) Create and upload

Create new javascript file and name it anything you wish. For example wp123.js and paste this code:

function paste(name)
{document.commentform.comment.value+="<strong>"+name+"</strong>\n";}
function Insert(text){
if (text!="") paste4("<blockquote>"+text+"</blockquote>\n", 0);
}
function paste4(text, flag){
if (document.commentform) {
if ((document.selection)&&(flag)) {
document.commentform.comment.focus();
document.commentform.document.selection.createRange().text = text;
} else document.commentform.comment.value += text;
}
}
function get_selection() {
if(navigator.userAgent.search(/webkit/i) > -1) {
selection = window.getSelection();
} else {
if (document.getSelection){
selection = document.getSelection();
selection = selection.replace(/\r\n\r\n/gi, "_doublecaret_");
selection = selection.replace(/\r\n/gi, " ");
while (selection.indexOf("  ") !=-1) selection = selection.replace(/  /gi, "");
selection = selection.replace(/_doublecaret_/gi, "\r\n\r\n");
} else {
selection = document.selection.createRange().text;
}
}
}

The paste function is for pasting the comment author nickname in comment field. The rest of the code is for quotation. Upload this file to your theme’s folder.

2) Call this javascript file

Now we have to add this javascript file to your website. For this, paste this code into the header section of your theme:

<script type="text/javascript" src="http://YOURSITE-AND-PATH-OF-SCRIPT/wp123.js"></script>

Change http://YOURSITE-AND-PATH-OF-SCRIPT with the path of your script. If the file is in your theme’s folder you can use this code:

<script type=”text/javascript” src=”<?php bloginfo(’template_directory’); ?>/js/tab.js”></script>

3) Edit your theme

This is the last step of our tutorial. Open your theme’s comments.php and find the <form> tag. Add name attribute called commentform:

<form name=”commentform” ….. > …. </form>

Now use this code:

<a style="cursor:hand" onclick="paste('<?php comment_author() ?>')">Paste Username</a>

where you want the “Past Usename” text to be shown. This code must be added inside the comment loop. The same for quote text code:

<a href=”javascript:Insert(selection)” onmousedown=”get_selection()”>Click here</a> to past the text!

We are done. Have fun!

Download the javascript file: javascript file (110)

Leave a Reply