


Implementation example of using AJAX technology to submit comments in WordPress_javascript skills
I have always been interested in the research on Ajax interaction in WordPress, and I have always paid attention to this technology. When talking about WordPress Ajax, I have to talk about comment Ajax submission. As a blog and forum comment, Ajax submission can not only improve the user experience. , and can also significantly reduce server expenses. After all, it is much simpler to output a single comment than to reorganize and output a page. Although the number of visits has been relatively low now and there is no problem of server pressure, I, who have always paid attention to user experience, certainly cannot give up such an opportunity to improve user experience. I spent an afternoon today and completed the preliminary submission of Ajax comments on this theme.
Go straight to the point and get to the code: (principles and ideas at the end)
Please adjust the following code according to the different structure of your own theme.
WordPress Ajax Submit Comment PHP Code
Add the following section to the theme function.php file.
//以下大部分代码出自 yinheli 经由该部分代码,排除部分错误、优化精简得出以下代码。 //yinheli博客不做了,所以这里就不给链接了。 //Edited by XiangZi DEC.17TH 2011 function fail($s) {//虚拟错误头部分 header('HTTP/1.0 500 Internal Server Error'); echo $s; exit; } function ajax_post_comment_slow (){ fail('用不用说这么快?想好了再说!'); } //评论太快输出代码。 add_filter('comment_flood_trigger','ajax_post_comment_slow', 0); //挂一个评论太快,返回内容的钩子 function ajax_comment(){ // Ajax php 响应部分代码 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) ) { //这一套判断貌似抄的 wp 源代码 。详见: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('火星人?注册个?'); } $comment_type = ''; if ( get_option('require_name_email') && !$user->ID ) { if ( 6> strlen($comment_author_email) || '' == $comment_author ) fail('Oopps,名字[Name]或邮箱[email]不对。'); elseif ( !is_email($comment_author_email)) fail('Oopps,邮箱地址[Email]不对。'); } if ( '' == $comment_content ) fail('是不是应该写点什么再提交?'); // 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('评论重复了!有木有!'); } $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('博主你也敢冒充?'); } else { fail('博主你也敢冒充?'); } } } $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);//这是我的调用评论函数,换成你的函数名。 die(); } } add_action('init', 'ajax_comment');
Javascript code
Note: The following code requires Jquery framework support.
Add the following part to the javascript onload code.
if (jQuery('#commentform').length) { jQuery('#commentform').submit(function(){ // 截获提交动作 //ID为 commentform 的表单提交时发生的函数,也就是整个留言输入框 form 的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) { //发生错误时 jQuery('#commenterror').html(request.responseText); jQuery('#commentload').hide(); //隐藏 submit jQuery('#commenterror').fadeIn(); //显示 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: The code still needs improvement. Because there is no time, it has not evolved further.
CSS code
Add css optionally.
#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 submit data
php responds and outputs the results
Javascript gets the result and displays
Idea:
After clicking the submit button, Javascript intercepts the submission action
Intercept the submitted data (Name, Email, Web, Comment-text)
Use Javascript Jquery to simulate a browser submitting a POST (Name, Email, Web, Comment-text) request to WordPress
Construct a function to accept requests in the Function.php file, that is, the ajax_comment function in this column
If the request has no errors, the correct result will be output
If there is an error in the request, output the error result
Javascript to get correct results, dynamically added to the comment list
Javascript obtains error results and dynamically adds them to the submission prompt bar
Improvements
In terms of style, I really don’t have any sense of beauty, so I’m still learning.
The submit button should be grayed out and invalid for 3 seconds after it is clicked until the return result is obtained. This was not noticed before because I was testing on this machine and the submission was completed instantly. I discovered it during the remote test, but if I want to change it, I still have to change it. It needs to be tested. If the time is too tight, I won’t change it. I will improve it if I have the opportunity.
Summary
Because of the freedom and diversity of comment styles in WordPress themes, it seems that there has never been a universal AJAX comment plug-in,
Some experts can only publish their ideas and some common core codes while optimizing their blogs,
So if you want to implement some cool functions, you need an expert to help you,
Otherwise, you can only study code hard and hope that one day you can accumulate a lot of knowledge.
Please submit your own comments to verify the effect.

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



PHP and Flutter are popular technologies for mobile development. Flutter excels in cross-platform capabilities, performance and user interface, and is suitable for applications that require high performance, cross-platform and customized UI. PHP is suitable for server-side applications with lower performance and not cross-platform.

WordPress posts are stored in the /wp-content/uploads folder. This folder uses subfolders to categorize different types of uploads, including articles organized by year, month, and article ID. Article files are stored in plain text format (.txt), and the filename usually includes its ID and title.

WordPress template files are located in the /wp-content/themes/[theme name]/ directory. They are used to determine the appearance and functionality of the website, including header (header.php), footer (footer.php), main template (index.php), single article (single.php), page (page.php), Archive (archive.php), category (category.php), tag (tag.php), search (search.php) and 404 error page (404.php). By editing and modifying these files, you can customize the appearance of your WordPress website

The most stable WordPress version is the latest version because it contains the latest security patches, performance enhancements, and introduces new features and improvements. In order to update to the latest version, log into your WordPress dashboard, go to the Updates page and click Update Now.

Build an autocomplete suggestion engine using PHP and Ajax: Server-side script: handles Ajax requests and returns suggestions (autocomplete.php). Client script: Send Ajax request and display suggestions (autocomplete.js). Practical case: Include script in HTML page and specify search-input element identifier.

WordPress requires registration. According to my country's "Internet Security Management Measures", websites that provide Internet information services within the country must register with the local provincial Internet Information Office, including WordPress. The registration process includes steps such as selecting a service provider, preparing information, submitting an application, reviewing and publishing, and obtaining a registration number. The benefits of filing include legal compliance, improving credibility, meeting access requirements, ensuring normal access, etc. The filing information must be true and valid, and must be updated regularly after filing.

WordPress uses MySQL as its article database, its main functions include: storing articles, comments, users and website configuration data. The data tables include: wp_posts (articles), wp_postmeta (metadata), wp_comments (comments), wp_commentmeta (comment metadata), wp_users (users). The database can be accessed and managed via phpMyAdmin or the command line, and it is crucial to back up the database regularly to prevent data loss.

To delete a WordPress theme template, first log into your dashboard, then go to Appearance > Theme Editor, select the theme you want to delete, click Delete and confirm, and optionally activate the new theme.
