为wordpress增加自定义小工具让热门文章按浏览量显示

核心提示:为wordpress增加自定义小工具让热门文章按浏览量显示。 一、首先是在functions.php里面增加浏览量的代码: // function to display number of posts. function getPostV...

为wordpress增加自定义小工具让热门文章按浏览量显示。

一、首先是在functions.php里面增加浏览量的代码:

// function to display number of posts.
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 to 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);
}
}

// Add it to a column in WP-Admin
add_filter('manage_posts_columns', 'posts_column_views');
add_action('manage_posts_custom_column', 'posts_custom_column_views',5,2);
function posts_column_views($defaults){
$defaults['post_views'] = __('Views');
return $defaults;
}
function posts_custom_column_views($column_name, $id){
if($column_name === 'post_views'){
echo getPostViews(get_the_ID());
}
}

二、将主题固定的模块函数提取出来,放到单独的模版文件中。

比如将下面这段“热门文章排行【浏览量】”代码,粘贴到新建的:widget_hot_views.php文件模版中,

热门文章代码:

<?php $popular = new WP_Query('post_status="publish"&meta_key="post_views_count"&orderby=meta_value&posts_per_page=10'); ?>
<div id="hot-views-posts"><h3>热门排行</h3><ul>
<?php while ($popular->have_posts()) : $popular->the_post(); ?>
<li><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></li>
<?php endwhile; ?>
</ul>
</div>

三、打开主题的functions.php,添加:

if( function_exists( 'register_sidebar_widget' ) ) {
register_sidebar_widget('WPMBY热门排行【浏览量】','wpmby_hot_views');
}

及:

function wpmby_hot_views() {
include(TEMPLATEPATH . '/widget_hot_views.php');

}

之后,打开Wordpress后台小工具页面,会多出个小工具“WPMBY热门排行【浏览量】”,与默认小工具一样可任意拖拽到侧边widget中,加上相应的样式基本就大功造成了。

在线客服