10 Useful WordPress Commentary Tricks
- Transfer
Many blogs openly neglect comment sections. But this is fundamentally wrong, since comments are nothing more than the interaction of authors with readers. In this article, we will share 10 great tips and secrets with which to help the blog comment section reach the level that it actually deserves.
1. We create action links for comments
Problem. Regardless of the presence of mandatory approval of comments before publication, some of the entries always have to be edited, deleted or marked as spam. By default, WordPress offers the “Edit” link for comments (using the “edit_comment_link ()” function), without providing “Delete” or “Spam”. I suggest adding them.
Decision. First you need to create a function. Paste the code below into the file “functions.php”: After saving the file “functions.php”, open “comments.php” and add the specified code to the places where the links “Delete” and “Spam” should appear. Both should go into the comment loop. In most topics, the function "edit_comment_link ()" is provided. In this case, the code is added immediately after it. Code analysis.
function delete_comment_link($id) {
if (current_user_can('edit_post')) {
echo '| del ';
echo '| spam';
}
}
delete_comment_link(get_comment_ID());
First of all, we, of course, are convinced that the user has permission to edit comments. After confirming it, links are displayed that allow you to delete the comment or mark it as spam. Pay attention to the function "admin_url ()", with which you can get the URL of the blog administrator.
2. Separate trackbacks from comments
Problem. Are there too many trackbacks in the recordings? Personally, yes. On the one hand, it’s great because readers can see which articles from other blogs link to yours. On the other hand, their excessive number makes it difficult to follow the discussion. In such a situation, of course, it makes sense to separate the trackbacks from the comments, especially if the “Reply” function provided in WordPress 2.7 is not used.
Decision. Find in the topic and edit the file "comments.php". Find a comment loop that looks something like this: Now replace it with the code below: Code analysis.
foreach ($comments as $comment) : ?>
// Comments are displayed here
endforeach;
foreach ($comments as $comment) : ?>
endforeach;
In principle, absolutely nothing complicated. The function "get_comment_type ()" tells the type - a regular comment or a trackback. It’s enough for us to create two HTML lists, filling the first with regular comments, and the second with trackbacks.
3. Get rid of HTML links in comments
Problem. Bloggers will never miss the opportunity to advertise their brainchild, and spammers have not disappeared yet. I am always terribly annoyed by the incredible number of links in the comments, as a rule, which have nothing to do with the issue. By default, WordPress comments URLs turn into links. Fortunately, those who are tired of links no less than me can fix this.
Decision. Just open the “function.php” file and paste the code below: When you save the file, remember to mentally say goodbye to links and other extraneous HTML snippets in the comments. Code analysis.
function plc_comment_post( $incoming_comment ) {
$incoming_comment['comment_content'] = htmlspecialchars($incoming_comment['comment_content']);
$incoming_comment['comment_content'] = str_replace( "'", ''', $incoming_comment['comment_content'] );
return( $incoming_comment );
}
function plc_comment_display( $comment_to_display ) {
$comment_to_display = str_replace( ''', "'", $comment_to_display );
return $comment_to_display;
}
add_filter('preprocess_comment', 'plc_comment_post', '', 1);
add_filter('comment_text', 'plc_comment_display', '', 1);
add_filter('comment_text_rss', 'plc_comment_display', '', 1);
add_filter('comment_excerpt', 'plc_comment_display', '', 1);
First, we created two functions that replace HTML characters with HTML objects. After that, using the powerful add_filter () function, we attach the standard WordPress functions for processing comments to the two newly created functions. This ensures that in all added comments, HTML components are filtered out.
4. Add Twitter avatars to comments
Problem. For bloggers, the Twitter network is extremely useful due to the ability to both popularize their own blog and keep in touch with fellow bloggers and their own audience. The Twitter network is so popular that, instead of global avatars (gravatars), comments can be fully illustrated with Twitter avatars.
Decision.
1. First we get a functional file from here .
2. Then we unpack the archive on the hard drive and open the file “twittar.php”.
3. Having selected all its contents, we insert into the file “functions.php” related to the blog.
4. The last step is to open the file “comments.php” and find the loop of comments.
5. Insert the following line into the loop:
Code analysis. A couple of months ago at Smashing Magazinewww.smashingmagazine.com was unveiled with the awesome Twittar software module, which serves to incorporate Twitter avatars into WordPress blogs. Having received a huge amount of feedback from WpRecipes.com readers, I decided to turn the software module into a piece of code - for those who are more comfortable.
Of course, those who wish can simply install the add-in instead of editing the contents of the “function.php” file - the choice is entirely yours.
5. We highlight the author’s comments in style.
Problem. In posts with a large number of comments, it is not always easy to find the author’s comments and answers, especially if the blog does not have the “Threaded Comments” tree comment function implemented in WordPress 2.7. But there is still a way out: we’ll highlight the author’s comments in a different style and readers will quickly find all your answers.
Decision.
1. Open the “comments.php” file and find the loop of comments:
2. After this line, insert the following fragment: 3. Then find in the code a line representing the comments (it may be different depending on the topic):
$isByAuthor = false;
if($comment->comment_author_email == get_the_author_email()) {
$isByAuthor = true;
}
?>
4. Now we need to derive the class "authorcomment" for the author’s comments:
5. It remains to create a CSS class for the author’s comments. Open the “style.css” file and paste the code snippet into it. Replace the colors from the example as you like: Code analysis. The principle of operation of the proposed code is based on a comparison of the email addresses of the commenting entries with the address of the author. If it matches, $ isByAuthor is set to true. When displaying comments, the value of "$ isByAuthor" is checked. When returning true, an authorcomment class is added to the container. In Wordpress version 2.7 and higher, this task is simpler: just add the class “comment_class ();” in the DIV of the comment, which will automatically add the class “bypostauthor” in the case of comments on your own posts (special thanks to Nima!).
.authorcomment{
color:#fff;
font-weight:bold;
background:#068;
}
6. We display the total number of comments and the average per record
Problem. The WordPress console has information on the total number of comments received by the blog. But the mechanism to make it public, unfortunately, is absent. Displaying the total number of blog comments and their average number per entry can be very useful, especially if the blog has a page for potential advertisers.
Decision. Code analysis. The functions “wp_count_posts ()” and “get_comment_count ()” existing in version 2.5 make it easy to get, respectively, the total number of posts and comments on the WordPress blog. To calculate the average number of comments on a record, elementary arithmetic operations and the “PHP round ()” function are enough, which will provide us with an integer value.
$count_posts = wp_count_posts();
$posts = $count_posts->publish;
$count_comments = get_comment_count();
$comments = $count_comments['approved'];
echo "There's a total of ".$comments." comments on my blog, with an average ".round($comments/$posts)." comments per post.";
?>
7. Display the nth number of recent comments
Problem. By default, WordPress provides a widget that displays any number of recent comments on posts. This is great, but sometimes a similar feature is necessary in the absence of a widget.
Decision. The secret is very simple: paste the proposed code where you want to display a certain number of comments made by the last. Be sure to include the specific quantity on line 3 (after the expression “LIMIT SQL”). Code analysis.
$pre_HTML ="";
$post_HTML ="";
global $wpdb;
$sql = "SELECT DISTINCT ID, post_title, post_password, comment_ID, comment_post_ID, comment_author, comment_date_gmt, comment_approved, comment_type,comment_author_url, SUBSTRING(comment_content,1,30) AS com_excerpt FROM $wpdb->comments LEFT OUTER JOIN $wpdb->posts ON ($wpdb->comments.comment_post_ID = $wpdb->posts.ID) WHERE comment_approved = '1' AND comment_type = '' AND post_password = '' ORDER BY comment_date_gmt DESC LIMIT 10";
$comments = $wpdb->get_results($sql);
$output = $pre_HTML;
$output .= "\n";
foreach ($comments as $comment) {
$output .= "\n- ".strip_tags($comment->comment_author) .":" . "ID)."#comment-" . $comment->comment_ID . "\" title=\"on ".$comment->post_title . "\">" . strip_tags($comment->com_excerpt)."
";
}
$output .= "\n
";
$output .= $post_HTML;
echo $output;
?>
Here we will also use the "$ wpdb" object, but this time coupled with the get_results () method. After receiving comments from the WordPress database, we will use the “for” loop to compose them into an unordered HTML list. The variables $ pre_HTML and $ post_HTML initialized at the top of the fragment determine what content comes before and after the list of comments.
8. Avoid comment spam - just
Problem. Comment spam is a common headache. Akismet is a good solution, but why not immediately block spammers instead of flagging suspicious messages? The proposed code looks for the HTTP referrer request header (the page where the request came from) and automatically blocks the comment if it is incorrect or not defined.
Decision. Paste the following code into the “functions.php” file: That's all. Having saved the file, we bring the blog to a new level of protection against spam. Code analysis.
function check_referrer() {
if (!isset($_SERVER['HTTP_REFERER']) || $_SERVER['HTTP_REFERER'] == “”) {
wp_die( __('Please enable referrers in your browser, or, if you\'re a spammer, bugger off!') );
}
}
add_action('check_comment_flood', 'check_referrer');
The code automatically rejects requests to post comments coming from a browser (usually a bot) without an HTTP referrer request header. Validation is performed using the array "PHP $ _SERVER []". If the header is not defined or is invalid, the wp_die function is called, and the script terminates.
This function is bound to the function "check_comment_flood ()" implemented in WordPress. Thus, we can be sure that the call to the function "check_referrer ()" will be executed every time a comment is posted.
9. We support WordPress compatibility with versions below 2.7
Problem. The release of WordPress 2.7, released just a few months ago, introduced a fundamentally new comment system that allows them to be displayed in a tree form and displayed on different pages. Although this is very convenient, do not forget that many users have not yet updated their applications to version 2.8 or at least 2.7. The proposed code will open to all owners of version 2.7 and higher the convenience of the new comment system, while retaining the old functions for those who did not care about the update.
Decision. For this purpose, you will need two files. The first is a file with WordPress 2.7-supported comments “comments.php”. The second is a comment template for earlier versions of WordPress “legacy.comments.php”. Both files will be stored in the theme folder.
Add the following code to the “functions.php” file: Code analysis. This code creates the function "legacy_comments ()", bound to the standard function "comments_template". Each time WordPress accesses "comments_template ()", our function "legacy_comments ()" will be executed. In the absence of the “wp_list_comments ()” function, the code automatically downloads “legacy.comments.php” instead of “comments.php”.
add_filter('comments_template', 'legacy_comments');
function legacy_comments($file) {
if(!function_exists('wp_list_comments')) : // WP 2.7-only check
$file = TEMPLATEPATH.'/legacy.comments.php';
endif;
return $file;
}
?>
10. Display entries with the most comments for a certain time
Problem. The number of comments is a great way to measure the popularity of a blog, as well as a good filter for listing the most popular posts. It would be nice to limit the most popular entries to a specific period of time, for example, by displaying a list of the most-most for the last month.
Decision. Just paste the suggested code where you want to list the most popular entries. Do not forget to change the dates in line 3 to the relevant for you. Code analysis. First of all, we send an SQL query to the WordPress database using the "$ wpdb" object. Having obtained the results, we use the simple PHP-operator “foreach” to display the most popular records for a certain period in the form of an unordered HTML list. Original article: 10 Handy WordPress Comments Hacks
$result = $wpdb->get_results("SELECT comment_count,ID,post_title, post_date FROM $wpdb->posts WHERE post_date BETWEEN '2009-01-01' AND '2009-02-01' ORDER BY comment_count DESC LIMIT 0 , 10");
foreach ($result as $topten) {
$postid = $topten->ID;
$title = $topten->post_title;
$commentcount = $topten->comment_count;
if ($commentcount != 0) {
?>
}
?>
Article translation: 10 useful tricks for working with comments in WordPress
foreach ($comments as $comment) : ?>
endforeach;