WordPress根据文章阅读量赋热帖图标

仿照discuz论坛,当文章浏览量大于规定值,自动在文章的顶部加一个图标。

实现代码

适合WordPress美化,主题的浏览量一般都是views,将下面的代码添加到主题的function.php。

add_filter('the_content', 'display_hot_post_badge');
function display_hot_post_badge($content) {
    // 仅在非管理界面、非订阅源、非主页的单篇文章主查询中执行
    if (!is_admin() && is_singular() && is_main_query()) {
        $post_views = (int) get_post_meta(get_the_ID(), 'views', true);
        $view_threshold = 50; // 浏览阈值常量定义
        
        if ($post_views > $view_threshold) {
            $badge_html = '<img class="hot-post-badge" 
                              src="https://www.sxpik.com/media/2023/10/002.gif" //替换自己的链接
                              alt="热门内容" 
                              loading="lazy">';
            return $badge_html . $content;
        }
    }
    return $content;
}

// 添加响应式样式
add_action('wp_head', 'hot_post_badge_style');
function hot_post_badge_style() {
    echo '<style>
        .hot-post-badge {
            position: absolute;
            right: 10px;
            z-index: 10;
            max-width: 120px;
            pointer-events: none;
            opacity: 0.9;
            transition: opacity 0.3s ease;
        }
        @media (max-width: 768px) {
            .hot-post-badge {
                max-width: 80px;
                right: 5px;
            }
        }
    </style>';
}

 

 » 本文来自热心的夹友 Niuma 提供。

0 条回复 A文章作者 M管理员
    暂无讨论,说说你的看法吧
个人中心
购物车
优惠劵
今日签到
有新私信 私信列表
搜索