wordpress显示文章浏览次数和热门文章排行

因为wordpress没有内置的显示浏览次数的小工具,那么我们只有自己加一个功能或者下载一个插件,常见的显示浏览次数的插件有WP-PostViews等几种插件,很多人应该用过这块插件,我现在这款主题也用的这个,感觉还行吧。看个人喜欢,如果不喜欢用插件也可以使用加入代码的方 法。

可以将下面代码加入到functiuons.php中去。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
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 View”;
}
return $count . ‘ Views';
}
 
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 );
}
}

第二步,将如下代码插入single.php文件的主循环内

<?php setPostViews(get_the_ID()); ?>
<?php echo getPostViews(get_the_ID()); ?>

第三步,需要在哪个页面或者栏目显示文章的浏览次数,就在相应的模板文件(比如首页:index.php,分类目录页:archive.php,侧边栏:sidebar.php)里面添加上面第二行的代码即可。
2、WP-PostViews Plus有自带的小工具功能可以使用,挺方便的,不过一些代码控就喜欢精简就自己把代码嵌入到sidebar.php中就可以了。
在主题文件sidebar.php文件中的相应位位置添加代码
显示阅读次数最多的文章或页面:

<?php if (function_exists(‘get_most_viewed’)): ?>
<?php get_most_viewed(); ?>
<?php endif; ?>

只显示阅读次数最多的文章:

<?php if (function_exists(‘get_most_viewed’)): ?>
<?php get_most_viewed(‘post’); ?>
<?php endif; ?>

只想显示10篇阅读次数最多的文章:

<?php if (function_exists(‘get_most_viewed’)): ?>
<?php get_most_viewed(‘post’,10); ?>
<?php endif; ?>

在get_most_viewed 函数中的参数10决定要显示的篇数
显示显示某类别下的阅读次数最多的文章:

<?php if (function_exists(‘get_most_viewed_category’)): ?>
<?php get_most_viewed_category(the_catagory_ID(false)); ?>
<?php endif; ?>

在get_most_viewed_category函数类别ID决定显示的分类附<?php get_most_viewed(‘post’,8,0,true,true);?>函数详解:

主题中有这么一句函数,是用来引用“最受欢迎文章”的,后面一共有5个参数可供设置,说明如下:
post:可选post,page,both;
8:控制应用文章的数量;
0:截取文章标题长度,0表示不设置,不设置的话长标题就会自动换行,很难看;
true:显示文章,若改为 false 则不显示文章;
true:不显示搜索引擎机器人的查询次数,若改为 true 则全部显示==============================================

推荐装插件:WP-PostViews:下载地址:http://wordpress.org/extend/plugins/wp-postviews/

则通过调用the_views()函数:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
### Function: Display The Post Views
function the_views($display = true, $prefix = ”, $postfix = ”, $always = false) {
$post_views = intval(post_custom(‘views’));
$views_options = get_option(‘views_options’);
if ($always || should_views_be_displayed($views_options)) {
$output = $prefix.str_replace(‘%VIEW_COUNT%’, number_format_i18n($post_views), $views_options[‘template’]).$postfix;
if($display) {
echo apply_filters(‘the_views’, $output);
} else {
return apply_filters(‘the_views’, $output);
}
}
elseif (!$display) {
return ”;
}
}

© 版权声明
THE END
喜欢就支持一下吧
点赞0 分享