Implementation ideas and methods for WordPress Ajax comments submission

Source: Internet
Author: User

Although the current access volume has been relatively low, there is no server pressure problem, but I have always paid attention to user experience, of course, cannot give up such an opportunity to improve user experience. I took a leave of time this afternoon and submitted the Ajax comments on this topic for preliminary completion.

Let's get started with the code: (the principles and ideas are at the end)
You can adjust the following code based on the structure of your topic.

WordPress Ajax Submits Comments to PHP code

Add the following content to the topic function. php file.

The code is as follows: Copy code
// Most of the following code comes from yinheli. This code helps you eliminate some errors and streamline the code below.
// The yinheli blog does not work, so the link is not provided here.
// Edited by XiangZi DEC.17TH 2011
Function fail ($ s) {// virtual error header
Header ('http/1.0 500 Internal Server Error ');
Echo $ s;
Exit;
}
Function ajax_post_comment_slow (){
Fail ('needless to say, it's so fast? Let's talk about it! ');
}
// The comments output the code too quickly.
Add_filter ('comment _ flood_trigger ', 'Ajax _ post_comment_slow', 0 );
// Hook of the returned content when a comment is posted too quickly
Function ajax_comment (){
// Ajax php response code
If ($ _ POST ['action'] = 'Ajax _ comment '){
Global $ wpdb, $ db_check;
// Check DB
If (! $ Wpdb-> dbh ){
Echo ('Ur database has issues. Try again later .');
Die ();
        }
Nocache_headers ();
$ Comment_post_ID = (int) $ _ POST ['Comment _ post_ID '];
$ Status = $ wpdb-> get_row ("SELECT post_status, comment_status FROM $ wpdb-> posts where id = '$ comment_post_ID '");
If (empty ($ status-> comment_status )){
// Determine the wp source code that looks like a copy. For details, see include/comment. php.
Do_action ('comment _ id_not_found ', $ comment_post_ID );
Fail ('the post you are trying to comment on does not currently exist in The database .');
} Elseif ('closed '= $ status-> comment_status ){
Do_action ('comment _ closed ', $ comment_post_ID );;
Fail ('sorry, comments are closed for this item .');
} Elseif (in_array ($ status-> post_status, array ('Draft ', 'pending '))){
Do_action ('comment _ on_draft ', $ comment_post_ID );
Fail ('the post you are trying to comment on has not been published .');
}
$ Comment_author = trim (strip_tags ($ _ POST ['author']);
$ Comment_author_email = trim ($ _ POST ['email ']);
$ Comment_author_url = trim ($ _ POST ['URL']);
$ Comment_content = trim ($ _ POST ['comment']);
// If the user is logged in
$ User = wp_get_current_user ();
If ($ user-> ID ){
$ 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 '))
Fail ('Martian? Registered? ');
}
$ Comment_type = '';
If (get_option ('require _ name_email ')&&! $ User-> ID ){
If (6> strlen ($ comment_author_email) | ''= $ comment_author)
Fail ('opps, Name [Name] or email address [email] is incorrect. ');
Elseif (! Is_email ($ comment_author_email ))
Fail ('opps, Email address [Email] is incorrect. ');
}
If (''= $ comment_content)
Fail ('should I write something before submitting? ');
// Simple duplicate check
$ 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 )){
Fail ('repeat the comment! Yes! ');
}
$ Commentdata = compact ('comment _ post_ID ', 'comment _ author', 'comment _ author_email ', 'comment _ author_url', 'comment _ content ', 'comment _ type', 'User _ id ');
If (! $ User-> ID ){
$ Result_set = $ wpdb-> get_results ("SELECT display_name, user_email FROM $ wpdb-> users WHERE display_name = '". $ comment_author. "'OR user_email = '". $ comment_author_email. "'");
If ($ result_set ){
If ($ result_set [0]-> display_name = $ comment_author ){
Fail ('Do you dare to pretend to be a blogger? ');
} Else {
Fail ('Do you dare to pretend to be a blogger? ');
 }
 }
}
$ Comment_id = wp_new_comment ($ commentdata );
$ Comment = get_comment ($ comment_id );
 
If (! $ User-> ID ){
Setcookie ('comment _ author _ '. COOKIEHASH, $ comment-> comment_author, time () + 30000000, COOKIEPATH, COOKIE_DOMAIN );
Setcookie ('comment _ author_email _ '. COOKIEHASH, $ comment-> comment_author_email, time () + 30000000, COOKIEPATH, COOKIE_DOMAIN );
Setcookie ('comment _ author_url _ '. COOKIEHASH, clean_url ($ comment-> comment_author_url), time () + 30000000, COOKIEPATH, COOKIE_DOMAIN );
}
@ Header ('content-type: '. get_option ('HTML _ type').'; charset = '. get_option ('blog _ charset '));
Xz_comment ($ comment, null); // This is my function for calling comments. Replace it with your function name.
Die ();
}
}
Add_action ('init ', 'Ajax _ comment ');

Javascript code

Note: The following code requires support from the Jquery framework.
Add the following parts to the javascript onload code.

The code is as follows: Copy code
If (jQuery ('# commentform'). length ){
JQuery ('# commentform'). submit (function (){
// Intercepts the submission action
// The function that occurs when a form with the ID of commentform is submitted, that is, the ID of the form in the entire message input box.
Var ajaxCommentsURL = window. location. href;
JQuery. ajax ({
Url: ajaxCommentsURL,
Data: jQuery ('# commentform'). serialize () +' & action = ajax_comment ',
Type: 'post ',
BeforeSend: function (){
JQuery ('# commenterror'). hide ();
JQuery ('# commentload'). fadeIn ();
},
Error: function (request) {// when an error occurs
Jquery('your commenterror'your .html (request. responseText );
JQuery ('# commentload'). hide (); // hide submit
JQuery ('# commenterror'). fadeIn (); // displays error
},
Success: function (data ){
JQuery ('textarea '). each (function (){
This. value = '';
});
JQuery ('# commenterror'). fadeOut ();
If (jQuery (". commentlist li. comment"). first (). length! = 0) {jQuery (". commentlist li. comment"). first (). before (data )}
Else {jQuery ("ol. commentlist"). append (data )}
JQuery (". commentlist li. comment"). first (). hide (0, function () {$ (this). slideDown (1000 )});
JQuery ('# cmt-submit '). attr ('disabled ', true0000.css ({"background-color": "# 6C6C6C", "color": "# E0E0E0 "});
JQuery ('# commentload'). fadeOut (1600 );
SetTimeout (function (){
Jquery('{cmt-submit'}.removeattr('disabled'}.css ({"background-color": "#0086C5", "color": "# FFFFFF "});
},3000 );
            }
});
Return false;
});
}

Note: there is still a need for code improvement, because there is no time, so there is no further evolution.

CSS code

Add css randomly.

The code is as follows: Copy code
# Commentload, # commenterror {
Display: none;
Margin: 5px 0 0 0;
Color: # D29A04;
Float: left;
Font-size: 16px;
Padding: 0 0 0 20px;
}
# Commentload {
Background: url ("img/loading.gif") no-repeat bottom left;
}
# Commenterror {
Background: url ("img/error.png") no-repeat bottom left;
}

Principles and ideas

Principle:
Javascript data submission
Php response and output results
Javascript returns and displays
Ideas:
After you click the submit button, Javascript intercepts the submission action.
Intercepted data (Name, Email, Web, and Comment-text)
Using Javascript Jquery to simulate a browser to submit POST (Name, Email, Web, Comment-text) requests to WordPress
The Function. php file constructs a request-receiving Function, that is, the ajax_comment Function in this column.
If no error is returned, the correct result is output.
If an error occurs in the request, an error is returned.
Javascript gets the correct result and dynamically adds it to the comment list.
Javascript gets the error result and dynamically adds it to the submission prompt bar.
Improvement

The submit button should be grayed out three seconds after it is clicked to get the returned result. It was not noticed that the submission was completed in an instant due to local testing, we found it during the remote test, but we still need to test it if we want to change it. If it is too short, we will not change it. We have the opportunity to improve it.

Summary

Because of the freedom and diversity of comment styles in WordPress themes, it seems that there is no universal AJAX comment plug-in so far,
Some experts can only announce their ideas and some general core code while optimizing their blogs,
So if you want to implement some cool functions, or someone else will help you,
Otherwise, you can only learn the code well and look forward to accumulating some details one day.
For the effect, please submit your own comments for verification.

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.