You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

74 lines
1.7 KiB

<?php
/**
* 文章浏览量统计功能
*/
// 防止直接访问
if (!defined('ABSPATH')) {
exit;
}
/**
* 获取文章浏览量
*
* @param int $postID 文章ID
* @return string 浏览量
*/
function nenghui_get_post_views($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;
}
/**
* 设置/增加文章浏览量
*
* @param int $postID 文章ID
*/
function nenghui_set_post_views($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, '1');
} else {
$count++;
update_post_meta($postID, $count_key, $count);
}
}
/**
* 自动增加浏览量(当访问文章详情页时)
*/
function nenghui_track_post_views() {
if (is_single()) {
global $post;
if (isset($post->ID)) {
nenghui_set_post_views($post->ID);
}
}
}
add_action('wp_head', 'nenghui_track_post_views');
/**
* 在后台文章列表显示浏览量列
*/
function nenghui_posts_column_views($defaults) {
$defaults['post_views'] = '浏览量';
return $defaults;
}
add_filter('manage_posts_columns', 'nenghui_posts_column_views');
function nenghui_posts_custom_column_views($column_name, $id) {
if ($column_name === 'post_views') {
echo nenghui_get_post_views($id);
}
}
add_action('manage_posts_custom_column', 'nenghui_posts_custom_column_views', 10, 2);