WordPress 分类标签页面浏览数统计

本文对比了四种WordPress分类浏览统计方法:自定义字段法最简单,性能高但功能基础;数据库表法最专业,性能高且功能完整;插件方案功能丰富但性能中等;AJAX无刷新法性能较高且支持实时统计。推荐数据库表法,并详细介绍了自定义字段法的实现代码和样式美化方案。

WordPress基础教程
阅读时间: 320 分钟
最后更新时间:2026年2月17日

📊 实现方法对比

方法难度性能功能推荐度
自定义字段简单基础统计⭐⭐⭐⭐
数据库表中等完整统计⭐⭐⭐⭐⭐
插件方案简单中等功能丰富⭐⭐⭐
AJAX无刷新较高中等实时统计⭐⭐⭐⭐

🔧 方法一:自定义字段法(最简单)

1.1 核心代码

// 添加到主题 functions.php
function count_category_views($category_id) {
    // 确保只在分类/标签页面执行
    if (!is_category() && !is_tag()) {
        return;
    }
    
    $current_id = 0;
    
    if (is_category()) {
        $current_id = get_queried_object_id();
    } elseif (is_tag()) {
        $current_id = get_queried_object_id();
    }
    
    if ($current_id) {
        $count_key = 'category_views_count';
        $count = get_term_meta($current_id, $count_key, true);
        
        if ($count == '') {
            $count = 0;
            delete_term_meta($current_id, $count_key);
            add_term_meta($current_id, $count_key, '1');
        } else {
            $count++;
            update_term_meta($current_id, $count_key, $count);
        }
    }
}
add_action('wp_head', 'count_category_views');

// 获取浏览数函数
function get_category_views($term_id) {
    $count = get_term_meta($term_id, 'category_views_count', true);
    return $count ? $count : 0;
}

// 显示浏览数短代码
function category_views_shortcode($atts) {
    $atts = shortcode_atts(array(
        'term_id' => 0,
        'label' => '浏览:',
        'show_icon' => true
    ), $atts);
    
    if (!$atts['term_id']) {
        if (is_category() || is_tag()) {
            $atts['term_id'] = get_queried_object_id();
        } else {
            return '';
        }
    }
    
    $views = get_category_views($atts['term_id']);
    $icon = $atts['show_icon'] ? '<i class="fas fa-eye"></i> ' : '';
    
    return '<span class="category-views">' . $icon . $atts['label'] . number_format($views) . '</span>';
}
add_shortcode('category_views', 'category_views_shortcode');

1.2 样式美化

/* 添加到主题样式表 */
.category-views {
    display: inline-block;
    padding: 5px 12px;
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    color: white;
    border-radius: 20px;
    font-size: 13px;
    font-weight: 500;
    box-shadow: 0 4px 15px rgba(0, 0, 0, 0.1);
    transition: all 0.3s ease;
}

.category-views:hover {
    transform: translateY(-2px);
    box-shadow: 0 6px 20px rgba(0, 0, 0, 0.15);
}

.category-views i {
    margin-right: 5px;
    font-size: 12px;
}

🗃️ 方法二:数据库表法(最专业)

2.1 创建数据库表

// 创建统计表
function create_category_views_table() {
    global $wpdb;
    $table_name = $wpdb->prefix . 'category_views';
    $charset_collate = $wpdb->get_charset_collate();
    
    $sql = "CREATE TABLE IF NOT EXISTS $table_name (
        id bigint(20) NOT NULL AUTO_INCREMENT,
        term_id bigint(20) NOT NULL,
        views_count bigint(20) NOT NULL DEFAULT 0,
        last_viewed datetime DEFAULT CURRENT_TIMESTAMP,
        PRIMARY KEY (id),
        UNIQUE KEY term_id (term_id),
        KEY views_count (views_count)
    ) $charset_collate;";
    
    require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
    dbDelta($sql);
}
add_action('after_setup_theme', 'create_category_views_table');
register_activation_hook(__FILE__, 'create_category_views_table');

2.2 完整统计系统

class Category_Views_Counter {
    
    private $table_name;
    
    public function __construct() {
        global $wpdb;
        $this->table_name = $wpdb->prefix . 'category_views';
        
        add_action('wp_head', array($this, 'track_view'));
        add_action('wp_ajax_nopriv_save_view', array($this, 'save_view_ajax'));
        add_action('wp_ajax_save_view', array($this, 'save_view_ajax'));
        add_action('wp_enqueue_scripts', array($this, 'enqueue_scripts'));
    }
    
    // 追踪浏览
    public function track_view() {
        if (!is_category() && !is_tag()) {
            return;
        }
        
        $term_id = get_queried_object_id();
        
        // 检查是否已记录(防止刷新重复计数)
        if (!isset($_SESSION['viewed_categories'])) {
            $_SESSION['viewed_categories'] = array();
        }
        
        if (in_array($term_id, $_SESSION['viewed_categories'])) {
            return;
        }
        
        $_SESSION['viewed_categories'][] = $term_id;
        
        // 使用AJAX保存,不阻塞页面加载
        ?>
        <script>
        jQuery(document).ready(function($) {
            var data = {
                action: 'save_view',
                term_id: <?php echo $term_id; ?>,
                security: '<?php echo wp_create_nonce("save_view_nonce"); ?>'
            };
            
            // 延迟发送请求
            setTimeout(function() {
                $.post('<?php echo admin_url('admin-ajax.php'); ?>', data, function(response) {
                    console.log('View counted');
                });
            }, 1000);
        });
        </script>
        <?php
    }
    
    // AJAX保存浏览
    public function save_view_ajax() {
        check_ajax_referer('save_view_nonce', 'security');
        
        $term_id = intval($_POST['term_id']);
        
        if ($term_id) {
            $this->increment_views($term_id);
        }
        
        wp_die();
    }
    
    // 增加浏览数
    private function increment_views($term_id) {
        global $wpdb;
        
        $exists = $wpdb->get_var($wpdb->prepare(
            "SELECT id FROM {$this->table_name} WHERE term_id = %d", 
            $term_id
        ));
        
        if ($exists) {
            $wpdb->query($wpdb->prepare(
                "UPDATE {$this->table_name} SET views_count = views_count + 1, last_viewed = NOW() WHERE term_id = %d",
                $term_id
            ));
        } else {
            $wpdb->insert(
                $this->table_name,
                array(
                    'term_id' => $term_id,
                    'views_count' => 1,
                    'last_viewed' => current_time('mysql')
                ),
                array('%d', '%d', '%s')
            );
        }
    }
    
    // 获取浏览数
    public function get_views($term_id) {
        global $wpdb;
        
        $views = $wpdb->get_var($wpdb->prepare(
            "SELECT views_count FROM {$this->table_name} WHERE term_id = %d",
            $term_id
        ));
        
        return $views ? intval($views) : 0;
    }
    
    // 获取热门分类
    public function get_popular_categories($limit = 10, $days = 30) {
        global $wpdb;
        
        $query = $wpdb->prepare(
            "SELECT cv.term_id, cv.views_count, t.name, t.slug
             FROM {$this->table_name} cv
             LEFT JOIN {$wpdb->terms} t ON cv.term_id = t.term_id
             WHERE cv.last_viewed >= DATE_SUB(NOW(), INTERVAL %d DAY)
             ORDER BY cv.views_count DESC
             LIMIT %d",
            $days,
            $limit
        );
        
        return $wpdb->get_results($query);
    }
    
    // 注册脚本
    public function enqueue_scripts() {
        wp_enqueue_script('jquery');
    }
}

// 初始化
new Category_Views_Counter();

2.3 管理界面

// 后台管理页面
function category_views_admin_page() {
    add_menu_page(
        '分类浏览统计',
        '浏览统计',
        'manage_options',
        'category-views',
        'category_views_admin_page_html',
        'dashicons-chart-line',
        30
    );
}
add_action('admin_menu', 'category_views_admin_page');

function category_views_admin_page_html() {
    global $wpdb;
    $table_name = $wpdb->prefix . 'category_views';
    
    // 获取统计数据
    $popular_categories = $wpdb->get_results(
        "SELECT cv.*, t.name, t.slug 
         FROM {$table_name} cv
         LEFT JOIN {$wpdb->terms} t ON cv.term_id = t.term_id
         ORDER BY cv.views_count DESC
         LIMIT 50"
    );
    
    // 获取今日浏览
    $today_views = $wpdb->get_var(
        "SELECT SUM(views_count) 
         FROM {$table_name} 
         WHERE DATE(last_viewed) = CURDATE()"
    );
    
    // 获取总浏览
    $total_views = $wpdb->get_var("SELECT SUM(views_count) FROM {$table_name}");
    ?>
    <div class="wrap">
        <h1>分类/标签浏览统计</h1>
        
        <div class="card" style="max-width: 300px; margin: 20px 0;">
            <h2>统计概览</h2>
            <p><strong>今日浏览:</strong> <?php echo number_format($today_views); ?></p>
            <p><strong>总浏览数:</strong> <?php echo number_format($total_views); ?></p>
        </div>
        
        <h2>热门分类/标签</h2>
        <table class="wp-list-table widefat fixed striped">
            <thead>
                <tr>
                    <th>排名</th>
                    <th>名称</th>
                    <th>Slug</th>
                    <th>浏览数</th>
                    <th>最后浏览</th>
                    <th>操作</th>
                </tr>
            </thead>
            <tbody>
                <?php if ($popular_categories): ?>
                    <?php $rank = 1; ?>
                    <?php foreach ($popular_categories as $item): ?>
                        <tr>
                            <td><?php echo $rank; ?></td>
                            <td>
                                <strong><?php echo esc_html($item->name); ?></strong>
                            </td>
                            <td><?php echo esc_html($item->slug); ?></td>
                            <td>
                                <span class="dashicons dashicons-visibility"></span>
                                <?php echo number_format($item->views_count); ?>
                            </td>
                            <td><?php echo date('Y-m-d H:i', strtotime($item->last_viewed)); ?></td>
                            <td>
                                <a href="<?php echo get_term_link($item->term_id); ?>" target="_blank">查看</a>
                                |
                                <a href="#" onclick="resetViews(<?php echo $item->term_id; ?>)">重置</a>
                            </td>
                        </tr>
                        <?php $rank++; ?>
                    <?php endforeach; ?>
                <?php else: ?>
                    <tr>
                        <td colspan="6">暂无数据</td>
                    </tr>
                <?php endif; ?>
            </tbody>
        </table>
        
        <h2>导出数据</h2>
        <button onclick="exportData()" class="button button-primary">导出CSV</button>
        
        <style>
        .stat-card {
            background: #fff;
            padding: 20px;
            border-radius: 5px;
            box-shadow: 0 1px 3px rgba(0,0,0,0.1);
            margin-bottom: 20px;
        }
        </style>
        
        <script>
        function resetViews(term_id) {
            if (confirm('确定要重置这个分类的浏览数吗?')) {
                jQuery.post(ajaxurl, {
                    action: 'reset_category_views',
                    term_id: term_id,
                    nonce: '<?php echo wp_create_nonce("reset_views"); ?>'
                }, function(response) {
                    location.reload();
                });
            }
        }
        
        function exportData() {
            window.location.href = '<?php echo admin_url("admin-ajax.php?action=export_category_views"); ?>';
        }
        </script>
    </div>
    <?php
}

// AJAX重置功能
function reset_category_views_ajax() {
    check_ajax_referer('reset_views', 'nonce');
    
    global $wpdb;
    $table_name = $wpdb->prefix . 'category_views';
    $term_id = intval($_POST['term_id']);
    
    $wpdb->update(
        $table_name,
        array('views_count' => 0),
        array('term_id' => $term_id),
        array('%d'),
        array('%d')
    );
    
    wp_die();
}
add_action('wp_ajax_reset_category_views', 'reset_category_views_ajax');

// 导出功能
function export_category_views() {
    global $wpdb;
    $table_name = $wpdb->prefix . 'category_views';
    
    $data = $wpdb->get_results(
        "SELECT t.name, t.slug, cv.views_count, cv.last_viewed
         FROM {$table_name} cv
         LEFT JOIN {$wpdb->terms} t ON cv.term_id = t.term_id
         ORDER BY cv.views_count DESC"
    );
    
    header('Content-Type: text/csv');
    header('Content-Disposition: attachment; filename="category_views_' . date('Ymd') . '.csv"');
    
    $output = fopen('php://output', 'w');
    fputcsv($output, array('名称', 'Slug', '浏览数', '最后浏览'));
    
    foreach ($data as $row) {
        fputcsv($output, array(
            $row->name,
            $row->slug,
            $row->views_count,
            $row->last_viewed
        ));
    }
    
    fclose($output);
    wp_die();
}
add_action('wp_ajax_export_category_views', 'export_category_views');

📱 前端显示功能

3.1 小工具显示热门分类

// 热门分类小工具
class Popular_Categories_Widget extends WP_Widget {
    
    public function __construct() {
        parent::__construct(
            'popular_categories_widget',
            '热门分类',
            array('description' => '显示浏览最多的分类/标签')
        );
    }
    
    public function widget($args, $instance) {
        global $wpdb;
        $table_name = $wpdb->prefix . 'category_views';
        
        $title = apply_filters('widget_title', $instance['title']);
        $limit = !empty($instance['limit']) ? $instance['limit'] : 5;
        $show_count = !empty($instance['show_count']) ? $instance['show_count'] : false;
        $days = !empty($instance['days']) ? $instance['days'] : 30;
        
        $categories = $wpdb->get_results($wpdb->prepare(
            "SELECT cv.term_id, cv.views_count, t.name, t.slug, tt.taxonomy
             FROM {$table_name} cv
             LEFT JOIN {$wpdb->terms} t ON cv.term_id = t.term_id
             LEFT JOIN {$wpdb->term_taxonomy} tt ON t.term_id = tt.term_id
             WHERE cv.last_viewed >= DATE_SUB(NOW(), INTERVAL %d DAY)
             ORDER BY cv.views_count DESC
             LIMIT %d",
            $days,
            $limit
        ));
        
        if (!$categories) {
            return;
        }
        
        echo $args['before_widget'];
        
        if ($title) {
            echo $args['before_title'] . $title . $args['after_title'];
        }
        
        echo '<ul class="popular-categories-list">';
        foreach ($categories as $category) {
            $term_link = get_term_link($category->term_id, $category->taxonomy);
            
            echo '<li class="popular-category-item">';
            echo '<a href="' . esc_url($term_link) . '" class="category-link">';
            echo esc_html($category->name);
            
            if ($show_count) {
                echo '<span class="views-count">' . number_format($category->views_count) . ' 浏览</span>';
            }
            
            echo '</a>';
            echo '</li>';
        }
        echo '</ul>';
        
        echo $args['after_widget'];
    }
    
    public function form($instance) {
        $title = !empty($instance['title']) ? $instance['title'] : '热门分类';
        $limit = !empty($instance['limit']) ? $instance['limit'] : 5;
        $show_count = !empty($instance['show_count']) ? $instance['show_count'] : false;
        $days = !empty($instance['days']) ? $instance['days'] : 30;
        ?>
        <p>
            <label for="<?php echo $this->get_field_id('title'); ?>">标题:</label>
            <input class="widefat" id="<?php echo $this->get_field_id('title'); ?>"
                   name="<?php echo $this->get_field_name('title'); ?>"
                   type="text" value="<?php echo esc_attr($title); ?>">
        </p>
        <p>
            <label for="<?php echo $this->get_field_id('limit'); ?>">显示数量:</label>
            <input class="tiny-text" id="<?php echo $this->get_field_id('limit'); ?>"
                   name="<?php echo $this->get_field_name('limit'); ?>"
                   type="number" value="<?php echo esc_attr($limit); ?>" min="1" max="20">
        </p>
        <p>
            <label for="<?php echo $this->get_field_id('days'); ?>">统计天数:</label>
            <input class="tiny-text" id="<?php echo $this->get_field_id('days'); ?>"
                   name="<?php echo $this->get_field_name('days'); ?>"
                   type="number" value="<?php echo esc_attr($days); ?>" min="1" max="365">
        </p>
        <p>
            <input class="checkbox" id="<?php echo $this->get_field_id('show_count'); ?>"
                   name="<?php echo $this->get_field_name('show_count'); ?>"
                   type="checkbox" <?php checked($show_count, 'on'); ?>>
            <label for="<?php echo $this->get_field_id('show_count'); ?>">显示浏览数</label>
        </p>
        <?php
    }
    
    public function update($new_instance, $old_instance) {
        $instance = array();
        $instance['title'] = (!empty($new_instance['title'])) ? strip_tags($new_instance['title']) : '';
        $instance['limit'] = (!empty($new_instance['limit'])) ? intval($new_instance['limit']) : 5;
        $instance['show_count'] = (!empty($new_instance['show_count'])) ? 'on' : '';
        $instance['days'] = (!empty($new_instance['days'])) ? intval($new_instance['days']) : 30;
        return $instance;
    }
}

// 注册小工具
function register_popular_categories_widget() {
    register_widget('Popular_Categories_Widget');
}
add_action('widgets_init', 'register_popular_categories_widget');

3.2 短代码功能

// 热门分类短代码
function popular_categories_shortcode($atts) {
    global $wpdb;
    $table_name = $wpdb->prefix . 'category_views';
    
    $atts = shortcode_atts(array(
        'limit' => 10,
        'show_count' => true,
        'days' => 30,
        'taxonomy' => 'category',
        'style' => 'list', // list, grid, cards
        'columns' => 3,
    ), $atts, 'popular_categories');
    
    $categories = $wpdb->get_results($wpdb->prepare(
        "SELECT cv.term_id, cv.views_count, t.name, t.slug, tt.description, tt.count as post_count
         FROM {$table_name} cv
         LEFT JOIN {$wpdb->terms} t ON cv.term_id = t.term_id
         LEFT JOIN {$wpdb->term_taxonomy} tt ON t.term_id = tt.term_id
         WHERE tt.taxonomy = %s AND cv.last_viewed >= DATE_SUB(NOW(), INTERVAL %d DAY)
         ORDER BY cv.views_count DESC
         LIMIT %d",
        $atts['taxonomy'],
        $atts['days'],
        $atts['limit']
    ));
    
    if (!$categories) {
        return '<p>暂无数据</p>';
    }
    
    ob_start();
    
    if ($atts['style'] === 'cards') {
        echo '<div class="popular-categories-cards" style="display: grid; grid-template-columns: repeat(' . $atts['columns'] . ', 1fr); gap: 20px;">';
        foreach ($categories as $category) {
            $term_link = get_term_link($category->term_id, $atts['taxonomy']);
            ?>
            <div class="category-card" style="background: white; border-radius: 10px; padding: 20px; box-shadow: 0 5px 15px rgba(0,0,0,0.1);">
                <h3 style="margin-top: 0;">
                    <a href="<?php echo esc_url($term_link); ?>" style="color: #333; text-decoration: none;">
                        <?php echo esc_html($category->name); ?>
                    </a>
                </h3>
                
                <?php if ($category->description): ?>
                <p style="color: #666; font-size: 14px; line-height: 1.4;">
                    <?php echo esc_html($category->description); ?>
                </p>
                <?php endif; ?>
                
                <div style="display: flex; justify-content: space-between; margin-top: 15px; font-size: 12px; color: #999;">
                    <span>
                        <i class="fas fa-eye"></i>
                        <?php echo number_format($category->views_count); ?> 浏览
                    </span>
                    <span>
                        <i class="fas fa-file-alt"></i>
                        <?php echo $category->post_count; ?> 篇文章
                    </span>
                </div>
            </div>
            <?php
        }
        echo '</div>';
    } else {
        echo '<ul class="popular-categories-list">';
        foreach ($categories as $category) {
            $term_link = get_term_link($category->term_id, $atts['taxonomy']);
            echo '<li>';
            echo '<a href="' . esc_url($term_link) . '">';
            echo esc_html($category->name);
            
            if ($atts['show_count']) {
                echo ' <span class="badge">' . number_format($category->views_count) . '</span>';
            }
            
            echo '</a>';
            echo '</li>';
        }
        echo '</ul>';
    }
    
    return ob_get_clean();
}
add_shortcode('popular_categories', 'popular_categories_shortcode');

📈 数据可视化

4.1 图表统计

// 图表数据接口
function category_views_chart_data() {
    global $wpdb;
    $table_name = $wpdb->prefix . 'category_views';
    
    $days = isset($_GET['days']) ? intval($_GET['days']) : 7;
    $limit = isset($_GET['limit']) ? intval($_GET['limit']) : 10;
    
    $data = $wpdb->get_results($wpdb->prepare(
        "SELECT t.name, SUM(cv.views_count) as total_views
         FROM {$table_name} cv
         LEFT JOIN {$wpdb->terms} t ON cv.term_id = t.term_id
         WHERE cv.last_viewed >= DATE_SUB(NOW(), INTERVAL %d DAY)
         GROUP BY cv.term_id
         ORDER BY total_views DESC
         LIMIT %d",
        $days,
        $limit
    ));
    
    wp_send_json(array(
        'labels' => wp_list_pluck($data, 'name'),
        'data' => wp_list_pluck($data, 'total_views'),
    ));
}
add_action('wp_ajax_category_views_chart', 'category_views_chart_data');
add_action('wp_ajax_nopriv_category_views_chart', 'category_views_chart_data');

// 图表短代码
function category_views_chart_shortcode($atts) {
    $atts = shortcode_atts(array(
        'days' => 7,
        'limit' => 10,
        'height' => 400,
    ), $atts);
    
    $chart_id = 'category-views-chart-' . wp_rand();
    
    ob_start();
    ?>
    <div style="position: relative; height: <?php echo $atts['height']; ?>px;">
        <canvas id="<?php echo $chart_id; ?>"></canvas>
    </div>
    
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
    <script>
    jQuery(document).ready(function($) {
        var ctx = document.getElementById('<?php echo $chart_id; ?>').getContext('2d');
        
        $.get('<?php echo admin_url("admin-ajax.php"); ?>', {
            action: 'category_views_chart',
            days: <?php echo $atts['days']; ?>,
            limit: <?php echo $atts['limit']; ?>
        }, function(response) {
            new Chart(ctx, {
                type: 'bar',
                data: {
                    labels: response.labels,
                    datasets: [{
                        label: '分类浏览数',
                        data: response.data,
                        backgroundColor: 'rgba(54, 162, 235, 0.5)',
                        borderColor: 'rgba(54, 162, 235, 1)',
                        borderWidth: 1
                    }]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    scales: {
                        y: {
                            beginAtZero: true,
                            ticks: {
                                callback: function(value) {
                                    return value.toLocaleString();
                                }
                            }
                        }
                    }
                }
            });
        });
    });
    </script>
    <?php
    return ob_get_clean();
}
add_shortcode('category_views_chart', 'category_views_chart_shortcode');

🔌 插件方案

5.1 使用现有插件

推荐插件:

1. Post Views Counter
   - 支持文章、页面、自定义文章类型
   - 可扩展支持分类、标签
   - 缓存友好
   - 多显示位置

2. KK Star Ratings
   - 评分+浏览统计
   - 短代码支持
   - 小工具支持
   - 多语言

3. Simple Page Visit Counter
   - 轻量级
   - 支持分类页面
   - AJAX统计
   - 无数据库写入

5.2 自定义插件结构

/*
Plugin Name: Category Views Counter
Plugin URI: https://yourwebsite.com/
Description: WordPress分类/标签页面浏览统计
Version: 1.0.0
Author: Your Name
*/

// 主类
class CategoryViewsCounter {
    
    private static $instance = null;
    private $table_name;
    
    public static function get_instance() {
        if (null === self::$instance) {
            self::$instance = new self();
        }
        return self::$instance;
    }
    
    private function __construct() {
        global $wpdb;
        $this->table_name = $wpdb->prefix . 'category_views';
        
        // 激活时创建表
        register_activation_hook(__FILE__, array($this, 'create_table'));
        
        // 初始化
        add_action('init', array($this, 'init'));
    }
    
    public function create_table() {
        // 同方法二的建表代码
    }
    
    public function init() {
        // 添加统计钩子
        add_action('wp_head', array($this, 'track_view'));
        
        // 注册短代码
        add_shortcode('category_views', array($this, 'views_shortcode'));
        add_shortcode('popular_categories', array($this, 'popular_shortcode'));
        
        // 注册小工具
        add_action('widgets_init', array($this, 'register_widget'));
        
        // 后台菜单
        if (is_admin()) {
            add_action('admin_menu', array($this, 'admin_menu'));
        }
    }
    
    // ... 其他方法
}

// 初始化插件
CategoryViewsCounter::get_instance();

📱 移动端优化

6.1 响应式设计

/* 移动端优化样式 */
@media (max-width: 768px) {
    .popular-categories-cards {
        grid-template-columns: repeat(2, 1fr) !important;
        gap: 15px;
    }
    
    .category-card {
        padding: 15px;
    }
    
    .category-views {
        font-size: 12px;
        padding: 4px 10px;
    }
    
    .popular-categories-list li {
        margin-bottom: 8px;
        padding: 8px 0;
        border-bottom: 1px solid #eee;
    }
}

@media (max-width: 480px) {
    .popular-categories-cards {
        grid-template-columns: 1fr !important;
    }
    
    .category-views {
        display: block;
        text-align: center;
        margin: 5px 0;
    }
}

🔍 SEO优化

7.1 Schema标记

// 添加Schema标记
function add_category_views_schema($term_id) {
    $views = get_category_views($term_id);
    $term = get_term($term_id);
    
    if ($views > 0) {
        $schema = array(
            '@context' => 'https://schema.org',
            '@type' => 'CollectionPage',
            'name' => $term->name,
            'description' => $term->description,
            'interactionStatistic' => array(
                '@type' => 'InteractionCounter',
                'interactionType' => 'https://schema.org/ViewAction',
                'userInteractionCount' => $views
            )
        );
        
        echo '<script type="application/ld+json">' . json_encode($schema) . '</script>';
    }
}
add_action('wp_head', function() {
    if (is_category() || is_tag()) {
        $term_id = get_queried_object_id();
        add_category_views_schema($term_id);
    }
});

🎯 最佳实践建议

统计策略

1. 避免重复计数:
   - 使用Session记录
   - AJAX延迟提交
   - 考虑IP限制

2. 性能优化:
   - 数据库索引优化
   - 定时缓存清理
   - 异步数据写入

3. 数据准确:
   - 排除爬虫访问
   - 排除管理员访问
   - 日志记录异常

部署建议

1. 新网站:使用方法一(简单)
2. 中型网站:使用方法二(完整)
3. 大型网站:插件+自定义
4. 高并发:Redis缓存+队列

📊 监控与分析

// 监控功能
function monitor_category_views() {
    global $wpdb;
    $table_name = $wpdb->prefix . 'category_views';
    
    // 监控异常增长
    $suspicious = $wpdb->get_results(
        "SELECT term_id, views_count, last_viewed
         FROM {$table_name}
         WHERE last_viewed >= DATE_SUB(NOW(), INTERVAL 1 HOUR)
         AND views_count > 1000
         ORDER BY views_count DESC
         LIMIT 10"
    );
    
    if ($suspicious) {
        // 发送警报
        wp_mail(
            get_option('admin_email'),
            '分类浏览异常警报',
            print_r($suspicious, true)
        );
    }
}
add_action('category_views_monitor', 'monitor_category_views');

// 定时执行
if (!wp_next_scheduled('category_views_monitor')) {
    wp_schedule_event(time(), 'hourly', 'category_views_monitor');
}

总结:选择适合您网站的统计方案,平衡功能需求和性能消耗。小型网站推荐方法一,中型网站推荐方法二,大型商业网站建议使用专业插件或定制开发。

这篇文章有用吗?

点击星号为它评分!

平均评分 0 / 5. 投票数: 0

到目前为止还没有投票!成为第一位评论此文章。

在AI里面继续讨论:

曾凤祥

曾凤祥

WordPress技术负责人
小兽WordPress凭借15年的WordPress企业网站开发经验,坚持以“为企业而生的WordPress服务”为宗旨,累计为10万多家客户提供高品质WordPress建站服务,得到了客户的一致好评。我们一直用心对待每一个客户,我们坚信:“善待客户,将会成为终身客户”。小兽WordPress能坚持多年,是因为我们一直诚信。

相关文章

如何让线上业务更上一层楼

还没有WordPress网站

还没有WordPress网站

不管你从事什么行业,WordPress都会为你提供一个专业的主题模板。在WordPress市场上有成千上万的免费主题,适合很多中小企业。

查看所有模板
已经有WordPress网站

已经有WordPress网站

小兽WordPress诚邀你一起学习WordPress,愿与各方携手升级改善您的WordPress网站,一起交流网站加速,网站优化等问题。

马上交个朋友
微信联系
chat 扫码联系
模板建站
挑选模板
网站定制
免费诊断
咨询热线
咨询热线

189-0733-7671

返回顶部