How to implement the WordPress ajax comment reply function

Source: Internet
Author: User
Tags require setcookie trim valid email address


First, put the comments-ajax.js and comments-ajax.php in the folder of the topic you are using;

Comments-ajax.js

The code is as follows: Copy code

Var I = 0, got =-1, len = document. getElementsByTagName ('script'). length;
While (I <= len & got =-1 ){
Var js_url = document. getElementsByTagName ('script') [I]. src,
Got = js_url.indexOf ('comments-ajax. Js'); I ++;
}
Var edit_mode = '1', // then ?? Mode ('1' = ?; '0' = no? )
Ajax_php_url = js_url.replace ('-ajax. Js','-ajax. Php '),
Wp_url = js_url.substr (0, js_url.indexOf ('WP-content ')),
Pic_sb = wp_url + 'WP-admin/images/wpspin_dark.gif ', // submit the icon
Pic_no = wp_url + 'WP-admin/images/no.png ',//?? Icon
Pic_ys = wp_url + 'WP-admin/images/yes.png ', // success icon
Txt1 = '<div id = "loading"> submitting ,? Wait... </div> ',
Txt2 = '<div id = "error" >#</div> ',
Txt3 = '"> submitted successfully ',
Edt1 = '. Before refreshing the page, you can <a rel = "nofollow" class = "comment-reply-link" href = "# edit" onclick = 'return addComment. moveForm ("',
Edt2 = ')'> edit </a> ',
Cancel_edit = 'cancel editation ',
Edit, num = 1, comm_array = []; comm_array.push ('');

JQuery (document). ready (function ($ ){
$ Comments = $ ('# comments-title ');//??? File ID
$ Cancel = $ ('# cancel-comment-reply-link'); cancel_text = $ cancel. text ();
$ Submit = $ ('# commentform # submit'); $ submit. attr ('disabled ', false );
$ ('# Comment'). after (txt1 + txt2); $ ('# loading'). hide (); $ ('# error'). hide ();
$ Body = (window. opera )? (Document. compatMode = "CSS1Compat "? $ ('HTML '): $ ('body'): $ ('HTML, body ');

/** Submit */
$ ('# Commentform'). submit (function (){
$ ('# Loading'). slideDown ();
$ Submit. attr ('disabled ', true). fadeTo ('low', 0.5 );
If (edit) $ ('# comment '). after ('<input type = "text" name = "edit_id" id = "edit_id" value = "' + edit + '" style = "display: none; "/> ');

/** Ajax */
$. Ajax ({
Url: ajax_php_url,
Data: $ (this). serialize (),
Type: $ (this). attr ('method '),

Error: function (request ){
$ ('# Loading'). slideUp ();
Certificate ('{error'{.slidedown().html ('' + request. responseText );
SetTimeout (function () {$ submit. attr ('disabled ', false ). fadeTo ('low', 1); $ ('# error '). slideUp ();}, 3000 );
},

Success: function (data ){
$ ('# Loading'). hide ();
Comm_array.push ($ ('# comment'). val ());
$ ('Textarea '). each (function () {this. value = ''});
Var t = addComment, cancel = t. I ('cel-comment-reply-link'), temp = t. I ('WP-temp-form-div '), respond = t. I (t. respondId), post = t. I ('comment _ post_ID '). value, parent = t. I ('comment _ parent '). value;

// Comments
If (! Edit & $ comments. length ){
N = parseInt ($ comments. text (). match (/d + /));
$ Comments. text ($ comments. text (). replace (n, n + 1 ));
  }

// Show comment
New_htm = '"id =" new_comm _' + num + '"> </';
New_htm = (parent = '0 ')? ('N' <ol style = "clear: both;" class = "commentlist '+ new_htm + 'ol> '): ('n' <ul class = "children '+ new_htm + 'Ul> ');

OK _htm = 'n' <span id = "success _ '+ num + txt3;
If (edit_mode = '1 '){
Div _ = (document. body. innerHTML. indexOf ('div-comment-') =-1 )? '': (Document. body. innerHTML. indexOf ('li-comment-') =-1 )? 'Div -':'');
OK _htm = OK _htm.concat (edt1, div _, 'comment-', parent,' "," ', parent,' "," respond "," ', post ,'", ', num, edt2 );
  }
OK _htm + = '</span> N ';

$ ('# Respond'). before (new_htm );
$ ('# New_comm _' + num). hide (). append (data );
$ ('# New_comm _' + num + 'Lil'). append (OK _htm );
$ ('# New_comm _' + num). fadeIn (4000 );

$ Body. animate ({scrollTop: $ ('# new_comm _' + num). offset (). top-200}, 900 );
Countdown (); num ++; edit = ''; $ ('*'). remove ('# edit_id ');
Cancel. style. display = 'none ';
Cancel. onclick = null;
T. I ('comment _ parent'). value = '0 ';
If (temp & respond ){
Temp. parentNode. insertBefore (respond, temp );
Temp. parentNode. removeChild (temp)
  }
  }
}); // End Ajax
Return false;
}); // End submit

/** Comment-reply.dev.js */
AddComment = {
MoveForm: function (commId, parentId, respondId, postId, num ){
Var t = this, div, comm = t. I (commId), respond = t. I (respondId), cancel = t. I ('cel-comment-reply-link'), parent = t. I ('comment _ parent'), post = t. I ('comment _ post_ID ');
If (edit) exit_prev_edit ();
Num? (
T. I ('Comment'). value = comm_array [num],
Edit = t. I ('New _ comm _ '+ num). innerHTML. match (/(comment-) (d +)/) [2],
$ New_sucs = $ ('# success _' + num), $ new_sucs.hide (),
$ New_comm = $ ('# new_comm _' + num), $ new_comm.hide (),
$ Cancel. text (cancel_edit)
): $ Cancel. text (cancel_text );

T. respondId = respondId;
PostId = postId | false;

If (! T. I ('WP-temp-form-div ')){
Div = document. createElement ('div ');
Div. id = 'WP-temp-form-div ';
Div. style. display = 'none ';
Respond. parentNode. insertBefore (div, respond)
  }

! Comm? (
Temp = t. I ('WP-temp-form-div '),
T. I ('comment _ parent'). value = '0 ',
Temp. parentNode. insertBefore (respond, temp ),
Temp. parentNode. removeChild (temp)
): Comm. parentNode. insertBefore (respond, comm. nextSibling );

$ Body. animate ({scrollTop: $ ('# respond'). offset (). top-180}, 400 );

If (post & postId) post. value = postId;
Parent. value = parentId;
Cancel. style. display = '';

Cancel. onclick = function (){
If (edit) exit_prev_edit ();
Var t = addComment, temp = t. I ('WP-temp-form-div '), respond = t. I (t. respondId );

T. I ('comment _ parent'). value = '0 ';
If (temp & respond ){
Temp. parentNode. insertBefore (respond, temp );
Temp. parentNode. removeChild (temp );
   }
This. style. display = 'none ';
This. onclick = null;
Return false;
};

Try {t. I ('Comment'). focus ();}
Catch (e ){}

Return false;
},

I: function (e ){
Return document. getElementById (e );
 }
}; // End addComment

Function exit_prev_edit (){
$ New_comm.show (); $ new_sucs.show ();
$ ('Textarea '). each (function () {this. value = ''});
Edit = '';
}

Var wait = 15, submit_val = $ submit. val ();
Function countdown (){
If (wait> 0 ){
$ Submit. val (wait); wait --; setTimeout (countdown, 1000 );
} Else {
$ Submit. val (submit_val). attr ('disabled ', false). fadeTo ('low', 1 );
Wait = 15;
  }
}

}); // End jQ

Comments-ajax.php

The code is as follows: Copy code

<? Php
/**
* WordPress? Are they short from u ?? S Ajax comments> WordPress-jQuery-Ajax-Comments v1.3 by Willin Kan.
* Www.111cn.net
*? Ming :??? Is the file created by the WP 3.0 root object? The wp-comment-post.php to modify, modify the place there are annotations .? WP litre ?, ? Note that it may be different.
*/

If ('post '! = $ _ SERVER ['request _ method']) {
Header ('allow: Post ');
Header ('http/1.1 405 Method Not allowed ');
Header ('content-Type: text/plain ');
Exit;
}

/** Sets up the WordPress Environment .*/
Require (dirname (_ FILE _). '/.../../wp-load.php'); // This comments-ajax.php is in the main ?? Expected? A, so the location is different

Nocache_headers ();

$ Comment_post_ID = isset ($ _ POST ['Comment _ post_ID '])? (Int) $ _ POST ['Comment _ post_ID ']: 0;

$ Post = get_post ($ comment_post_ID );

If (empty ($ post-> comment_status )){
Do_action ('comment _ id_not_found ', $ comment_post_ID );
Err (_ ('invalidcomment status .'));//? Exit change? Else e? Prompt
}

// Get_post_status () will get the parent status for attachments.
$ Status = get_post_status ($ post );

$ Status_obj = get_post_status_object ($ status );

If (! Comments_open ($ comment_post_ID )){
Do_action ('comment _ closed ', $ comment_post_ID );
Err (_ ('sorry, comments are closed for this item .'));//? Wp_die change? Else e? Prompt
} Elseif ('trash '= $ status ){
Do_action ('comment _ on_trash ', $ comment_post_ID );
Err (_ ('invalidcomment status .'));//? Exit change? Else e? Prompt
} Elseif (! $ Status_obj-> public &&! $ Status_obj-> private ){
Do_action ('comment _ on_draft ', $ comment_post_ID );
Err (_ ('invalidcomment status .'));//? Exit change? Else e? Prompt
} Elseif (post_password_required ($ comment_post_ID )){
Do_action ('comment _ on_password_protected', $ comment_post_ID );
Err (_ ('password protected '));//? Exit change? Else e? Prompt
} Else {
Do_action ('pre _ comment_on_post ', $ comment_post_ID );
}

$ Comment_author = (isset ($ _ POST ['author'])? Trim (strip_tags ($ _ POST ['author']): null;
$ Comment_author_email = (isset ($ _ POST ['email '])? Trim ($ _ POST ['email ']): null;
$ Comment_author_url = (isset ($ _ POST ['URL'])? Trim ($ _ POST ['URL']): null;
$ Comment_content = (isset ($ _ POST ['comment'])? Trim ($ _ POST ['comment']): null;
$ Edit_id = (isset ($ _ POST ['edit _ id'])? $ _ POST ['edit _ id']: null; // Extract edit_id

// If the user is logged in
$ User = wp_get_current_user ();
If ($ user-> ID ){
If (empty ($ user-> display_name ))
$ User-> display_name = $ user-> user_login;
$ Comment_author = $ wpdb-> escape ($ user-> display_name );
$ Comment_author_email = $ wpdb-> escape ($ user-> user_email );
$ Comment_author_url = $ wpdb-> escape ($ user-> user_url );
If (current_user_can ('unfiltered _ html ')){
If (wp_create_nonce ('unfiltered-html-comment _ '. $ comment_post_ID )! = $ _ POST ['_ wp_unfiltered_html_comment']) {
Kses_remove_filters (); // start with a clean slate
Kses_init_filters (); // set up the filters
  }
 }
} Else {
If (get_option ('comment _ registration') | 'private' = $ status)
Err (_ ('sorry, you must be logged in to post a comment .'));//? Wp_die change? Else e? Prompt
}

$ Comment_type = '';

If (get_option ('require _ name_email ')&&! $ User-> ID ){
If (6> strlen ($ comment_author_email) | ''= $ comment_author)
Err (_ ('Error: please fill the required fields (name, email ).'));//? Wp_die change? Else e? Prompt
Elseif (! Is_email ($ comment_author_email ))
Err (_ ('Error: please enter a valid email address .'));//? Wp_die change? Else e? Prompt
}

If (''= $ comment_content)
Err (_ ('Error: please type a comment .'));//? Wp_die change? Else e? Prompt

// Add :?? Prompt function
Function err ($ ErrMsg ){
Header ('http/1.1 405 Method Not allowed ');
Echo $ ErrMsg;
Exit;
}

// Add :? Re-check z ?? Function
$ Dupe = "SELECT comment_ID FROM $ wpdb-> comments WHERE comment_post_ID = '$ comment_post_ID' AND (comment_author = '$ comment_author '";
If ($ comment_author_email) $ dupe. = "OR comment_author_email = '$ comment_author_email '";
$ Dupe. = ") AND comment_content = '$ comment_content' LIMIT 1 ";
If ($ wpdb-> get_var ($ dupe )){
Err (_ ('Duplicate comment detected; it looks as though you & #8217; ve already said that! '));
}

// Add :? Z query ?? Feature too fast
If ($ lasttime = $ wpdb-> get_var ($ wpdb-> prepare ("SELECT comment_date_gmt FROM $ wpdb-> comments WHERE comment_author = % s order by comment_date desc limit 1 ", $ comment_author ))){
$ Time_lastcomment = mysql2date ('u', $ lasttime, false );
$ Time_newcomment = mysql2date ('u', current_time ('mysql', 1), false );
$ Flood_die = apply_filters ('comment _ flood_filter ', false, $ time_lastcomment, $ time_newcomment );
If ($ flood_die ){
Err (_ ('you are posting comments too quickly. Slow down .'));
 }
}

$ Comment_parent = isset ($ _ POST ['Comment _ parent'])? Absint ($ _ POST ['Comment _ parent']): 0;

$ Commentdata = compact ('comment _ post_ID ', 'comment _ author', 'comment _ author_email ', 'comment _ author_url', 'comment _ content ', 'comment _ type', 'comment _ parent', 'User _ id ');

// Add :? Z query ?? Is it being used ??, Update or new ??
If ($ edit_id ){
$ Comment_id = $ commentdata ['Comment _ id'] = $ edit_id;
Wp_update_comment ($ commentdata );
} Else {
$ Comment_id = wp_new_comment ($ commentdata );
}

$ Comment = get_comment ($ comment_id );
If (! $ User-> ID ){
$ Comment_cookie_lifetime = apply_filters ('comment _ cookie_lifetime ', 30000000 );
Setcookie ('comment _ author _ '. COOKIEHASH, $ comment-> comment_author, time () + $ comment_cookie_lifetime, COOKIEPATH, COOKIE_DOMAIN );
Setcookie ('comment _ author_email _ '. COOKIEHASH, $ comment-> comment_author_email, time () + $ comment_cookie_lifetime, COOKIEPATH, COOKIE_DOMAIN );
Setcookie ('comment _ author_url _ '. COOKIEHASH, esc_url ($ comment-> comment_author_url), time () + $ comment_cookie_lifetime, COOKIEPATH, COOKIE_DOMAIN );
}

// $ Location = empty ($ _ POST ['redirect _ to'])? Get_comment_link ($ comment_id): $ _ POST ['redirect _ to']. '# comment-'. $ comment_id; // cancel the original refresh redirection.
// $ Location = apply_filters ('comment _ post_redirect ', $ location, $ comment );

// Wp_redirect ($ location );

$ Comment_depth = 1; // prepared for the class attribute of the comment
$ Tmp_c = $ comment;
While ($ tmp_c-> comment_parent! = 0 ){
$ Comment_depth ++;
$ Tmp_c = get_comment ($ tmp_c-> comment_parent );
}

// Which of the following is ?? Formula ?? Does not include "reply". Do you want to use your template style? Copy override ?.
?>
<Li <? Php comment_class ();?> Id = "li-comment-<? Php comment_ID ();?> ">
<Div id = "comment-<? Php comment_ID ();?> ">
<Div class = "comment-author vcard">
<? Php echo get_avatar ($ comment, $ size = '40', $ default = '<path_to_url>');?>
<? Php printf (_ ('<cite class = "fn"> % s </cite> <span class = "says"> says: </span> '), get_comment_author_link ();?>
</Div>
<? Php if ($ comment-> comment_approved = '0'):?>
<Em> <? Php _ e ('Your comment is awaiting moderation. ');?> </Em>
<Br/>
   
<? Php endif;?>

<Div class = "comment-meta commentmetadata"> <a href = "<? Php echo esc_url (get_comment_link ($ comment-> comment_ID);?> "> <? Php printf (_ ('% 1 $ s at % 2 $ s'), get_comment_date (), get_comment_time ();?> </A> <? Php edit_comment_link (_ ('(Edit)'), '');?> </Div>

<Div class = "comment-body"> <? Php comment_text ();?> </Div>

</Div>

Second, open header. php in the topic folder and find:

The code is as follows: Copy code

<? Php if (is_singular () wp_enqueue_script ('comment-reply');?>

To:

<? Php if (is_singular () {?>
<Script type = "text/javascript" src = "http://ajax.googleapis.com/ajax/libs/jquery/1.2.3/jquery.min.js"> </script>
<Script type = "text/javascript" src = "<? Php bloginfo ('Template _ directory');?> /Comments-ajax.js "> </script>
<? Php }?>

Okay, that's simple. Clear Cache and refresh.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.