Встретить данный блок на сегодняшний день можно на многих сайтах, в частности под управлением CMS WordPress. Большая часть из них выводиться при помощи плагинов, доступных в репозиториях продукта.
Попробуем вывести блок «Популярные статьи» не используя плагинов. В качестве критерия выборки статей будем использовать количество просмотров статей.
В файл functions.php необходимо добавить следующие функции:
function setPostViews($postID) {
$count_key = 'post_views_count';
$count = get_post_meta($postID, $count_key, true);
if($count==''){
$count = 0;
delete_post_meta($postID, $count_key);
add_post_meta($postID, $count_key, '0');
}else{
$count++;
update_post_meta($postID, $count_key, $count);
}
}
function getPostViews($postID){
$count_key = 'post_views_count';
$count = get_post_meta($postID, $count_key, true);
if($count==''){
delete_post_meta($postID, $count_key);
add_post_meta($postID, $count_key, '0');
return "0";
}
return $count;
}
Счетчик просмотров необходимо вызывать внутри цикла loop, в файле single.php
<?php setPostViews(get_the_ID()); ?>
Выводим блок:
<div>
<h3>Популярное</h3>
<ul>
<?php
$args = array(
'numberposts' => 10,
'meta_key' => 'post_views_count',
'orderby' => 'meta_value_num',
'order' => 'DESC'
);
query_posts($args);
while ( have_posts() ) : the_post();
?>
<li><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></li>
<?php endwhile; wp_reset_query(); ?>
</ul>
</div>