Example implementation of comment submission using AJAX technology in WordPress

  • 2020-11-30 08:08:33
  • OfStack

1 straight interested in WordPress Ajax interaction research, also 1 straight very focus on this aspect of the technology, when it comes to WordPress Ajax have to comment about Ajax submitted, as a blog, BBS comment Ajax submission can not only improve the user experience, can also sharply reduce server expenditure, proportion of output, after all, a single comment new organization output 1 page is much simple. Although the number of visitors is now relatively low, there is no server pressure, but 1 to focus on user experience I, of course, can not give up such an opportunity to improve the user experience. The Ajax comments on this topic have been submitted to the public for 1 afternoon.

Straight to the point, straight to the code :(principles and ideas at the end)
Please adjust the following code according to the structure of your theme.

WordPress Ajax Submit comments PHP code
Add the following section to the topic function.php file.


// Most of the following code comes from  yinheli  Through this part of the code, eliminate some errors, optimize and streamline the following code. 
//yinheli The blog is not doing, so there are no links here. 
//Edited by XiangZi DEC.17TH 2011
function fail($s) {// Virtual error header section 
  header('HTTP/1.0 500 Internal Server Error');
  echo $s;
  exit;
}
function ajax_post_comment_slow (){
 fail(' You don't have to do it so fast? Think it over! ');
}
// Comments too fast output code. 
add_filter('comment_flood_trigger','ajax_post_comment_slow', 0);
// hang 1 A comment too fast returns the content of the hook 
function ajax_comment(){
// Ajax php  Response part code 
if($_POST['action'] == 'ajax_comment') {
  global $wpdb, $db_check;
    // Check DB
    if(!$wpdb->dbh) {
      echo('Our 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) ) {
// this 1 The set of judgments seems to be copied  wp  The source code   . 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(' The martians? To register a ?');
}
$comment_type = '';
if ( get_option('require_name_email') && !$user->ID ) {
  if ( 6> strlen($comment_author_email) || '' == $comment_author )
    fail('Oopps, The name [Name] Or email [email] Not right. ');
  elseif ( !is_email($comment_author_email))
    fail('Oopps, Email address [Email] Not right. ');
}
if ( '' == $comment_content )
  fail(' Should I write something before I submit? ');
// 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(' The comment repeats ! Is there any !');
}
$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 pretend to be a blogger? ');
 } else {
 fail(' Do you 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 call comment function, change it to your function name. 
 die();
}
}
add_action('init', 'ajax_comment');

Javascript code in
Note: The following code requires Jquery framework support.
Add the following to the javascript onload code.


if (jQuery('#commentform').length) {
  jQuery('#commentform').submit(function(){  
//  Intercept commit action 
//ID for  commentform  Is the function that occurs when the form is submitted, that is, the entire message input box  form  the ID . 
 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('#commenterror').html(request.responseText);
        jQuery('#commentload').hide();  // hidden  submit
        jQuery('#commenterror').fadeIn(); // According to  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', true).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 improvement in the code, and because there is no time, there is no evolution.

CSS code
css optional section added.


#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 ;
}

Principle and thinking
Principle:
Javascript submits data
php responds and outputs the results
Javascript gets the results and displays
Ideas:
After clicking the submit button, Javascript intercepts the submit action
Interception of submitted data (Name, Email, Web, ES53en-ES54en)
Javascript Jquery is used to simulate the browser to submit WordPress of POST (Name, Email, Web, ES62en-ES63en) request
In the Function.php file, construct a function that accepts the request, namely the ajax_comment function in this column
If the request is error-free, output the correct result
If there is an error in the request, print the error result
Javascript gets the correct result and dynamically adds it to the comment list
Javascript gets an error result and adds it dynamically to the submit prompt bar
To improve the
In terms of style, I really don't have a lot of beauty, so I'm learning.
After clicking the submit button for 3 seconds after getting the returned result, it should be in the state of grey failure. Before this point, I didn't notice that the submission was completed at the moment in the local test, but I found it in the remote test. However, if I want to change it, I still need to do the test, because the time is too tight.

conclusion
Because of the freedom and diversity of WordPress comment styles, it seems that there is no universal AJAX comment plugin until now.
1 some experts can only optimize their own blog, the idea and part of the common core code to do 1 under the announcement,
So if you want to do something really cool or if you don't have someone really smart to help you,
Otherwise, you'll just have to learn the code and expect to accumulate more and more in one day.
Please submit your own comments for verification.


Related articles: