标签: wordpress top10

  • wordpress调用30天内浏览最多10个文章的方法

    在WordPress中调用30天内浏览量最高的10篇文章,需要结合浏览量统计功能和查询实现。以下是实现方法:

    首先,你需要有文章浏览量统计功能。可以使用插件(如WP-PostViews),或自己实现计数功能。假设你已经有了存储浏览量的自定义字段(通常是post_views)。

    然后,可以使用以下代码查询30天内浏览量最高的10篇文章:

    // 获取30天内浏览量最高的10篇文章
    function get_popular_posts_30days($count = 10) {
        // 计算30天前的时间戳
        $thirty_days_ago = strtotime('-30 days');
        
        $args = array(
            'post_type' => 'post',
            'post_status' => 'publish',
            'posts_per_page' => $count,
            'date_query' => array(
                array(
                    'after' => $thirty_days_ago,
                    'inclusive' => true,
                ),
            ),
            'meta_key' => 'post_views', // 存储浏览量的自定义字段
            'orderby' => 'meta_value_num',
            'order' => 'DESC',
        );
        
        $popular_posts = new WP_Query($args);
        
        return $popular_posts;
    }
    
    // 在模板中使用
    $popular_posts = get_popular_posts_30days(10);
    if ($popular_posts->have_posts()) {
        echo '<ul class="popular-posts">';
        while ($popular_posts->have_posts()) {
            $popular_posts->the_post();
            ?>
            <li>
                <a href="<?php the_permalink(); ?>"><?php the_title(); ?></a>
                <span class="views-count">浏览量: <?php echo get_post_meta(get_the_ID(), 'post_views', true); ?></span>
            </li>
            <?php
        }
        echo '</ul>';
        wp_reset_postdata();
    }

    如果你的WordPress没有浏览量统计功能,可以添加以下代码到主题的functions.php中实现基础的浏览量统计:

    // 记录文章浏览量
    function set_post_views($postID) {
        $count_key = 'post_views';
        $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 get_post_views($postID) {
        $count_key = 'post_views';
        $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 . " 次浏览";
    }
    
    // 在单篇文章页调用统计
    function track_post_views($post_id) {
        if (!is_single()) return;
        if (empty($post_id)) {
            global $post;
            $post_id = $post->ID;    
        }
        set_post_views($post_id);
    }
    add_action('wp_head', 'track_post_views');

    使用时,将第一个代码块中的查询部分放在你想要显示热门文章的模板位置(如sidebar.php、home.php等)即可。

    这种方法的优点是简单直接,缺点是浏览量统计比较基础,可能会因为缓存等原因不够准确。如果需要更精确的统计,可以考虑使用GoogleAnalyticsAPI结合WordPress查询来实现。