There are many functionalities on the web that were just begging to be AJAXified. Whether it be voting on a poll or simply commenting on a blog post, there's really no reason to reload an entire page for something so simple. This blog has featured AJAX comments in WordPress for years, but only recently did I find the most optimized way to process those comments. Here's how to handle the WordPress PHP side of AJAX comment systems.
网路上有许多功能只是乞求AJAX化。 无论是对民意调查投票还是对博客帖子进行评论,实际上都没有理由为整个简单的事情重新加载整个页面。 这个博客多年来一直在WordPress中使用AJAX注释,但是直到最近我才找到最优化的方式来处理这些注释。 这是处理AJAX注释系统的WordPress PHP方面的方法。
PHP (The PHP)
Add the following function with your theme's function.php file:
在主题的function.php文件中添加以下函数:
// Method to handle comment submissionfunction ajaxComment($comment_ID, $comment_status) { // If it's an AJAX-submitted comment if(isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest'){ // Get the comment data $comment = get_comment($comment_ID); // Allow the email to the author to be sent wp_notify_postauthor($comment_ID, $comment->comment_type); // Get the comment HTML from my custom comment HTML function $commentContent = getCommentHTML($comment); // Kill the script, returning the comment HTML die($commentContent); }}
The function above receives the new comment ID (the comment is already posted to the DB at this point) and comment_status, if you care to know it. If the comment was submitted via AJAX, the comment metadata is retrieved, wp_notify_postauthor
is called to send an email notification about the new comment to the author, and the last step is outputting the formatted comment HTML, which my formatComment
function completes. The last step is adding a WordPress actions to trigger the function above:
如果您想知道的话,上面的函数将接收新的注释ID(此时注释已发布到DB)和comment_status。 如果评论是通过AJAX提交的,则检索评论元数据, wp_notify_postauthor
向作者发送有关新评论的电子邮件通知,最后一步是输出格式化的评论HTML,这是我的formatComment
函数完成的。 最后一步是添加WordPress操作以触发上述功能:
// Send all comment submissions through my "ajaxComment" methodadd_action('comment_post', 'ajaxComment', 20, 2);
Now all new AJAX-submitted comments get filtered through the ajaxComment
method, outputting just the specific comment HTML, allowing you to insert the comment content into the relevant parent OL/UL element on the client side.
现在,所有新提交的AJAX提交的注释都通过ajaxComment
方法进行过滤,仅输出特定的注释HTML,从而使您可以将注释内容插入客户端的相关父OL / UL元素中。
In the past, I've allowed the entire page to load and that was....slow. Very slow. The method described above allows for easy PHP/AJAX comment handling, allows other relevenat comment processing methods (including emailing the author of the post), and immediately outputs the comment HTML. Who thought it could be so easy?!
过去,我允许加载整个页面,但速度很慢。 非常慢。 上述方法可简化PHP / AJAX注释处理,允许其他相关注释处理方法(包括通过电子邮件发送帖子作者),并立即输出注释HTML。 谁认为这可能是如此简单?
翻译自: