本组代码同样适用于Wordpress侧边栏调用带缩略图的热门文章列表。 以下是在WordPress中调用热门文章并显示特色图像的代码,根据阅读量(post views)排序: 文章目录 调用文章列表脚本 添加functions代码 添加CSS样式 使用说明 调用文章列表脚本 <?php // 获取热门文章的查询参数 $args = array( 'posts_per_page' => 5, // 显示文章数量 'meta_key' => 'post_views_count', // 文章阅读量的meta_key 'orderby' => 'meta_value_num', // 按照阅读量数值排序 'order' => 'DESC', // 降序排列 'post_status' => 'publish' // 仅显示已发布的文章 ); // 执行查询 $popular_posts = new WP_Query($args); // 判断是否有文章 if($popular_posts->have_posts()) : echo '<div class="popular-posts">'; echo '<h3>热门文章</h3>'; // 循环输出文章 while($popular_posts->have_posts()) : $popular_posts->the_post(); ?> <div class="popular-post-item"> <!-- 显示特色图像 --> <?php if(has_post_thumbnail()) : ?> <div class="post-thumbnail"> <a href="<?php the_permalink(); ?>"> <?php the_post_thumbnail('thumbnail'); ?> </a> </div> <?php endif; ?> <!-- 显示文章标题 --> <div class="post-title"> <a href="<?php the_permalink(); ?>"> <?php the_title(); ?> </a> </div> <!-- 显示阅读量 --> <div class="post-views"> 阅读量:<?php echo get_post_meta(get_the_ID(), 'post_views_count', true); ?> </div> </div> <?php endwhile; echo '</div>'; // 重置文章数据 wp_reset_postdata(); endif; ?> 添加functions代码 为了让这段代码正常工作,你还需要: 添加文章阅读量统计功能。在functions.php中添加以下代码: // 设置文章阅读量 function set_post_views() { if(is_single()) { $post_id = get_the_ID(); $count = get_post_meta($post_id, 'post_views_count', true); if($count == '') { delete_post_meta($post_id, 'post_views_count'); add_post_meta($post_id, 'post_views_count', 1); } else { update_post_meta($post_id, 'post_views_count', $count + 1); } } } add_action('wp_head', 'set_post_views'); 添加CSS样式 在你的主题样式文件中添加: .popular-posts { margin: 20px 0; } .popular-post-item { display: flex; align-items: center; margin-bottom: 15px; padding: 10px; border-bottom: 1px solid #eee; } .post-thumbnail { flex: 0 0 100px; margin-right: 15px; } .post-thumbnail img { width: 100%; height: auto; border-radius: 5px; } .post-title { flex: 1; } .post-title a { color: #333; text-decoration: none; font-weight: bold; } .post-views { font-size: 12px; color: #666; margin-top: 5px; } 使用说明 将第一段PHP代码放在你想显示热门文章的位置(如侧边栏模板文件中)。 将第二段代码(阅读量统计功能)添加到你主题的functions.php文件中。 将CSS样式代码添加到你的主题样式文件中。 这段代码会: 显示5篇最热门的文章(可以通过修改posts_per_page参数来调整数量) 每篇文章显示特色图像(如果有的话) 显示文章标题和阅读量 根据阅读量降序排序 添加基本的样式美化 你可以根据需要调整参数和样式,比如: 修改显示的文章数量 调整特色图像的大小 自定义CSS样式 添加更多文章信息(如发布日期、摘要等) 未经允许不得转载:泥人传说 » 【纯代码】wordpress调用热门文章并显示特色图像,根据阅读量排序,教程脚本附带相关的functions脚本和样式表。 wordpress侧边栏调用热门文章wordpress侧边栏调用热门文章列表wordpress脚本调用热门文章wordpress脚本调用热门文章列表wordpress调用带缩略图的热门文章wordpress调用带缩略图的热门文章列表wordpress调用热门文章wordpress调用热门文章列表 分享到: 赞(0)