Можно долго описывать пользу плагина “Топ комментаторов”, но одно могу сказать точно, если хотите сделать свой блог популярным в блогосфере и повысить трафик, то подобная функция будет весьма кстати. Обычно посетители на блоге не очень активно комментируют статьи, даже если они интересные. Но если установлен виджет топа комментаторов, то сразу же начинается движение и каждый хочет оказаться на верхней позиции рейтинга, чтобы все увидели ссылку на его сайт. Такая вот мотивация получается и главное, что все от этого выигрывают. И сейчас мы разберем, как реализовать блок комментаторов на блоге без плагина. Немного терпения и все получится. Итак, поехали.
Некоторые плагины можно заменять простой вставкой кода и это хорошее альтернативное решение, которое снижает нагрузку на сайт. Первое, что нужно сделать, это добавить код в файл functions.php. Если у вас нет такого файла, то его нужно создать и не забудьте про кодировку UTF-8 без BOM. Добавляем в файл этот код:
function sp_top_commentator(){ global $wpdb; $length = 0; $month = false $comment = true; $nofollow = true; $count = 9; $col = 3; $avatarSize = 40; $exceptionEmail = 'pochta@dom.ru, pochta2@mod.ru'; $results = $wpdb->get_results(' SELECT COUNT(comment_author_email) AS comments_count, comment_author_email, comment_author, comment_author_url FROM (select * from '.$wpdb->comments.' order by comment_ID desc) as pc WHERE comment_author_email != "" AND comment_type = "" AND comment_approved = 1 AND comment_author_email NOT IN ('.preg_replace('/([\w\d\.\-_]+@[\w\d\.\-_]+)(,? ?)/','"\\1"\\2',$exceptionEmail).')'. ($month ? 'AND month(comment_date) = month(now()) AND year(comment_date) = year(now())' : ''). 'GROUP BY comment_author_email ORDER BY comments_count DESC LIMIT '.$count ); $output = "<div class='top-comment'><table><tr>"; $i = 0; foreach($results as $result){ if ($i>=$col) { $output .= "</tr><tr>"; $i = 0; } $i++; $output .= "<td><div class='avatar-top'>" .get_avatar($result->comment_author_email,$avatarSize)."</div> <div class='avatar-comment'>"; if ($length and $length<mb_strlen($result->comment_author)) $result->comment_author = trim(mb_substr($result->comment_author, 0, $length)).'.'; if ($result->comment_author_url) if ($nofollow) $output .= "<a target='_blank' rel='nofollow' href='".$result->comment_author_url."'>".$result->comment_author."</a>"; else $output .= "<a target='_blank' href='".$result-> comment_author_url."'>".$result->comment_author."</a>"; else $output .= $result->comment_author; if ($comment) $output .= "(".$result->comments_count.")"; $output .= "<div style='clear:both;'></div></div></td>"; } if ($i<=$col) $output .= "</tr>"; $output .= "</table></div>"; echo $output; }
Теперь немного подробнее о функциях, которые прописаны в самом начале.
$length = 0; // Длина имени $month = false; // true - за текущий месяц, false - за все время $comment = true; // Показывать количество комментариев $nofollow = true; // ссылки nofollow $count = 9; // количество комментаторов $col = 3; // количество колонок $avatarSize = 40; // размер аватара в пикселях $exceptionEmail = 'mail1@dom.ru, mail2@mod.ru'; // исключить адреса
Мы вставили основные функции для отображения блока ТОП комментаторов и теперь давайте включим его там, где хотим видеть. Обычно для этого используют сайдбар. Нужно открыть на редактирование файл sidebar.php и вставить в него функцию:
<!--?php sp_top_commentator(); ?-->
Но это еще не все. Для того, чтобы каждый месяц были определены победители и, соответственно были расположены выше других в топе, нужно добавить еще один кусок кода, похожий на предыдущий. Вот он:
function sp_commentator_winners(){ global $wpdb; $length = 0 $comment = true $nofollow = true; $col = 3 $avatarSize = 40; $exceptionEmail = 'pochta@dom.ru, pochta2@mod.ru'; $countWinners = 3; $results = $wpdb->get_results(' SELECT COUNT(comment_author_email) AS comments_count, comment_author_email, comment_author, comment_author_url FROM (select * from '.$wpdb->comments.' order by comment_ID desc) as pc WHERE comment_author_email != "" AND comment_type = "" AND comment_approved = 1 AND comment_author_email NOT IN ('.preg_replace('/([\w\d\.\-_]+@[\w\d\.\-_]+)(,? ?)/','"\\1"\\2',$exceptionEmail).') AND month(comment_date) = month(now() - interval 1 month) GROUP BY comment_author_email ORDER BY comments_count DESC LIMIT '.$countWinners ); $output = "</pre> <div class="top-comment">"; $i = 0; foreach($results as $result){ if ($i>=$col) { $output .= ""; $i = 0; } $i++; $output .= " "; } if ($i<=$col) $output .= " "; $output .= " <table width="100%"> <tbody> <tr> <td> <div class="avatar-top">".get_avatar($result->comment_author_email,$avatarSize)." </div> <div class="avatar-comment">"; if ($length and $length<mb_strlen($result->comment_author)) $result->comment_author = trim(mb_substr($result->comment_author, 0, $length)).'.'; if ($result->comment_author_url) if ($nofollow) $output .= "<a href="".$result->comment_author_url."" target="_blank" rel="nofollow">".$result->comment_author."</a>"; else $output .= "<a href="".$result->comment_author_url." " target="_blank">".$result->comment_author."</a>"; else $output .= $result->comment_author; if ($comment) $output .= "(".$result->comments_count.")"; $output .= " <div style="clear: both;"></div> </div></td> </tr> </tbody> </table> </div> <pre> "; echo $output; }
Функция $countWinners говорит о том, сколько победителей выводить в блоке. По умолчанию установлено 3, но вы можете менять это значение на свое. И так же в sidebar.php добавляем функцию вывода победителей:
<!--?php sp_commentator_winners(); ?-->
Дело осталось за малым – красиво оформить блок топа комментаторов при помощи CSS стилей. Здесь, я думаю, к каждому шаблону придется писать свои стили, чтобы гармонично встроить блок в дизайн, но все же возможно кому-то даже не придется редактировать этот код:
.top-comment { height:100%; } .top-comment table { min-height: 100%; height:100%; width:100%; } .top-comment table tr { text-align:center; vertical-align: top; } .top-comment table td { padding:0 5px 15px 5px; } .top-comment .avatar-top img { padding: 3px; background: white; border-image: initial; border: 1px solid #D0D0BB; margin: 0 0 3px 0; } .top-comment .avatar-comment { font-size: 12px; }
Вот таким образом можно организовать конкурс среди комментаторов и повысить посещаемость своего блога. Надеюсь, что вам было все понятно. В принципе, сложного ничего здесь нет. Просто скопировать и вставить код в файлы своего шаблона.
Высоких вам конверсий!