📜 ⬆️ ⬇️

10 useful tricks to work with comments in WordPress

10        WordPress

In many blogs, sections with comments frankly neglected. But this is fundamentally wrong, since comments are nothing more than the interaction of authors with readers. In this article, we will share the 10th excellent tips and secrets by which the comments section of the blog will reach the level that he, in fact, deserves.

1. Create comments for links with actions



Problem. Regardless of the presence of mandatory approval of comments before posting, some of the entries always have to be edited, deleted or marked as spam. By default, WordPress offers an “Edit” link for comments (using the “edit_comment_link ()” function), without providing for “Delete” or “Spam”. I propose to add them.
')
Decision. First you need to create a function. Paste the code below into the “functions.php” file:

function delete_comment_link($id) {
if (current_user_can('edit_post')) {
echo '| <a href="'.admin_url("comment.php?action=cdc&c=$id").'">del</a> ';
echo '| <a href="'.admin_url("comment.php?action=cdc&dt=spam&c=$id").'">spam</a>';
}
}


After saving the file “functions.php”, open “comments.php” and where the “Delete” and “Spam” links should appear, add the specified code. Both must enter the comment loop. Most themes provide a “edit_comment_link ()” function. In this case, the code is added immediately after it.

delete_comment_link(get_comment_ID());

Code analysis First of all, we, of course, make sure that the user has permission to edit comments. After confirmation, links appear that allow you to delete a comment or mark it as spam. Notice the “admin_url ()” function, with which you can get the blog administrator URL.

2. Separate trackbacks from comments.



Problem. Too many trackbacks in the recordings? Personally, I have yes. On the one hand, this is great because readers can see which articles from other blogs link to yours. On the other hand, an excessive amount of them 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” feature provided in WordPress 2.7 is not used.

Decision. Find in the topic and edit the file "comments.php". Find a loop of comments that looks something like this:

foreach ($comments as $comment) : ?>
// Comments are displayed here
endforeach;


Now replace it with the code below:

<ul class="commentlist">
<?php //Displays comments only
foreach ($comments as $comment) : ?>

<?php $comment_type = get_comment_type(); ?>
<?php if($comment_type == 'comment') { ?>
<li>//Comment code goes here</li>
<?php }
endforeach;
</ul>
<ul>
<?php //Displays trackbacks only

foreach ($comments as $comment) : ?>
<?php $comment_type = get_comment_type(); ?>
<?php if($comment_type != 'comment') { ?>
<li><?php comment_author_link() ?></li>
<?php }
endforeach;
</ul>


Code analysis In principle, absolutely nothing complicated. The function “get_comment_type ()” reports the type - a regular comment or trackback. It’s enough for us to create two HTML lists by filling in the first one with regular comments, and the second one with trackbacks.

3. Get rid of HTML links in the comments.


HTML-
Problem. Bloggers will never miss a chance to advertise their offspring, and even spammers have not disappeared anywhere. I am always terribly annoyed by the incredible amount of links in the comments, as a rule, not having any relation to the question. By default, URLs in WordPress comments turn into links. Fortunately, those who are tired of links not less than me can fix it.

Decision. Just open the function.php file and paste in the code below:

function plc_comment_post( $incoming_comment ) {
$incoming_comment['comment_content'] = htmlspecialchars($incoming_comment['comment_content']);

$incoming_comment['comment_content'] = str_replace( "'", '&apos;', $incoming_comment['comment_content'] );
return( $incoming_comment );
}
function plc_comment_display( $comment_to_display ) {
$comment_to_display = str_replace( '&apos;', "'", $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);


After saving the file, do not forget to say goodbye in your mind to links and other extraneous HTML fragments in the comments.

Code analysis We first created two functions that replace HTML characters with HTML objects. After that, using the powerful “add_filter ()” function, we associate the standard WordPress functions for processing comments to the two newly created functions. This ensures that all added comments will filter the HTML components.

4. Add Twitter avatars to comments


Twitter
Problem. The Twitter network is extremely useful to bloggers due to the ability to both popularize their own blog and be in touch with fellow bloggers and their own audience. Twitter is so popular that, instead of global avatars (gravatars), comments can be illustrated with Twitter avatars.

Decision.
1. First we get a functional file from here .
2. Then unpack the archive on your hard drive and open the file “twittar.php”.
3. Selecting all its contents, paste into the blog-related file “functions.php”.
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:

<?php twittar('45', 'default.png', '#e9e9e9', 'twitavatars', 1, 'G'); ?>

Code analysis A couple of months ago, a stunning Twittar plug-in was introduced to Smashing Magazine www.smashingmagazine.com , which serves to include Twitter avatars in WordPress blogs. Having received a huge amount of feedback from WpRecipes.com readers, I decided to turn the software module into a code fragment - for those who are more comfortable.
Of course, those who wish can simply install the add-on instead of editing the contents of the file “function.php” - the choice is yours.

5. Select the style comments of the author



Problem. In posts with a large number of comments, it is not always easy to find the comments and answers of the author, especially if the blog does not have the tree-like comments feature “Threaded Comments” implemented in WordPress 2.7. But there is still a way out: let's highlight the author's comments in a different style - and readers will quickly find all your answers.

Decision.
1. Open the file “comments.php” and find the loop of comments:

<?php foreach comment as $comment) { ?>

2. After this line, insert the following fragment:

<?php
$isByAuthor = false;
if($comment->comment_author_email == get_the_author_email()) {
$isByAuthor = true;
}
?>


3. Then find a line in the code representing comments (it may be different depending on the topic):

<li class="<?php echo $oddcomment; ?>" id="comment-<?php comment_ID() ?>">

4. Now we need to display the “authorcomment” class for the author’s comments:

<li class="<?php echo $oddcomment; ?> <?php if($isByAuthor ) {
echo 'authorcomment';} ?>" id="comment-<?php comment_ID() ?>">


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 colors from sample as you see fit:

.authorcomment{
color:#fff;
font-weight:bold;
background:#068;
}


Code analysis The principle of operation of the proposed code is based on the comparison of e-mail addresses commenting entries with the address of the author. If the match is, $ isByAuthor is set to true. When displaying comments, the value of "$ isByAuthor" is checked. When “true” is returned, the class “authorcomment” is added to the container.
In Wordpress version 2.7 and above, this task is easier: simply add the “comment_class ();” class to the DIV comment, which will automatically add the “bypostauthor” class in case of comments to your own posts (special thanks to Nima!).

6. Display the total number of comments and the average per record



Problem. On the WordPress console there is information about the total number of comments received by the blog. But the mechanism to make it publicly available, unfortunately, is missing. Displaying the total number of comments on a blog and the average number of comments per post can be very useful, especially if the blog has a page for potential advertisers.

Decision.

<?php
$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.";
?>


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 to the record, elementary arithmetic operations and the “PHP round ()” function are enough to provide us with an integer value.

7. Display the n-th number of recent comments.


n-
Problem. By default, WordPress provides a widget that displays any number of recent comments to posts. This is great, but sometimes this 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 last. Do not forget to specify the specific number in line 3 (after the expression "LIMIT SQL").

<?php
$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<ul>";
foreach ($comments as $comment) {
$output .= "\n<li>".strip_tags($comment->comment_author) .":" . "<a href=\"" . get_permalink($comment->ID)."#comment-" . $comment->comment_ID . "\" title=\"on ".$comment->post_title . "\">" . strip_tags($comment->com_excerpt)."</a></li>";

}
$output .= "\n</ul>";
$output .= $post_HTML;
echo $output;
?>


Code analysis Here we also use the "$ wpdb" object, but this time along with the "get_results ()" method. After receiving comments from the WordPress database, use the loop "for" to link them into an unordered HTML list. Initialized at the top of the snippet, the variables $ pre_HTML and $ post_HTML determine which 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. In the file "functions.php", paste the code below:

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');


That's all. After saving the file, we bring the blog to a new level of protection against spam.

Code analysis The code automatically rejects requests for the publication of comments originating from a browser (usually a bot) without an HTTP referrer request header. The check is performed using the array "PHP $ _SERVER []". If the header is undefined or incorrect, the wp_die function is called and the script is terminated.
This function is bound to the “check_comment_flood ()” function implemented in WordPress. Thus, we can be sure that the call to the “check_referrer ()” function will be executed each time a comment is posted.

9. We support WordPress compatibility with versions below 2.7.


WordPress    2.7
Problem. In the release of WordPress 2.7 just a few months ago, a fundamentally new commenting system appeared, allowing you to display them in a tree-like form and display them on different pages. Although it 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 versions 2.7 and above the convenience of the new commenting system, retaining the old functions for those who have not taken care of 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 WordPress versions of legacy.comments.php. Both files will be stored in the theme folder.
In the file "functions.php" add the following code:

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


Code analysis This code creates a “legacy_comments ()” function bound to the standard “comments_template” function. Each time WordPress accesses "comments_template ()", our legacy_comments () function will be executed. In the absence of the “wp_list_comments ()” function, the code automatically loads “legacy.comments.php” instead of “comments.php”.

10. Display the entries with the most comments in a specific time.



Problem. Number of comments is a great way to measure the popularity of a blog, as well as a good filter for displaying a list of 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 recent months.

Decision. Just paste the proposed code where you want to list the most popular entries. Do not forget to change the dates in line 3 to the actual for you.

<ul>
<?php
$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) {
?>
<li><a href="<?php echo get_permalink($postid); ?>"><?php echo $title ?></a></li>

<?php }
}
?>
</ul>


Code analysis The first step is to send the SQL query to the WordPress database via the "$ wpdb" object. After receiving the results, we use a simple PHP “foreach” operator 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
Article translation: 10 useful tricks to work with comments in WordPress

Source: https://habr.com/ru/post/65691/


All Articles