如何在自定义主题的WordPress中整合热门文章代码到现有相关文章代码
相关文章与热门文章代码整合方案
现有相关文章代码
<div class="bmenu">相关文章</div> <div class="masonry"> <?php $related = get_posts( array( 'category__in' => wp_get_post_categories($post->ID), 'numberposts' => 6, 'post__not_in' => array($post->ID) ) ); if( $related ) { foreach( $related as $post ) { setup_postdata($post); get_template_part( 'includes/templates/loop', 'single' ); } } wp_reset_postdata(); ?> </div>
整合热门文章后的完整代码
方案1:分区块展示(推荐)
<!-- 相关文章区块 --> <div class="bmenu">相关文章</div> <div class="masonry"> <?php $related = get_posts( array( 'category__in' => wp_get_post_categories($post->ID), 'numberposts' => 6, 'post__not_in' => array($post->ID) ) ); if( $related ) { foreach( $related as $post ) { setup_postdata($post); get_template_part( 'includes/templates/loop', 'single' ); } } wp_reset_postdata(); ?> </div> <!-- 热门文章区块 --> <div class="bmenu">热门文章</div> <div class="masonry"> <?php // 按自定义浏览量字段排序,排除当前文章 $popular = get_posts( array( 'numberposts' => 6, 'post__not_in' => array($post->ID), 'meta_key' => 'post_views_count', // 对应记录浏览量的自定义字段 'orderby' => 'meta_value_num', 'order' => 'DESC', 'post_status' => 'publish' ) ); if( $popular ) { foreach( $popular as $post ) { setup_postdata($post); get_template_part( 'includes/templates/loop', 'single' ); } } wp_reset_postdata(); ?> </div>
方案2:合并到同一个容器展示
如果需要把两类文章放在同一个瀑布流容器里,可使用以下结构:
<div class="bmenu">相关文章 + 热门文章</div> <div class="masonry"> <?php // 先渲染相关文章 $related = get_posts( array( 'category__in' => wp_get_post_categories($post->ID), 'numberposts' => 6, 'post__not_in' => array($post->ID) ) ); if( $related ) { foreach( $related as $post ) { setup_postdata($post); get_template_part( 'includes/templates/loop', 'single' ); } } wp_reset_postdata(); // 再渲染热门文章 $popular = get_posts( array( 'numberposts' => 6, 'post__not_in' => array($post->ID), 'meta_key' => 'post_views_count', 'orderby' => 'meta_value_num', 'order' => 'DESC', 'post_status' => 'publish' ) ); if( $popular ) { foreach( $popular as $post ) { setup_postdata($post); get_template_part( 'includes/templates/loop', 'single' ); } } wp_reset_postdata(); ?> </div>
整合说明
- 结构保持一致:沿用原有
bmenu标题和masonry容器的布局逻辑,保证页面样式统一。 - 热门文章逻辑:通过自定义字段
post_views_count记录文章浏览量,以此作为排序依据筛选热门内容,同时排除当前文章避免重复。 - 复用渲染模板:两类文章均调用
includes/templates/loop-single.php模板,确保卡片样式统一。 - 避免变量冲突:每个查询结束后调用
wp_reset_postdata(),重置全局文章变量,防止后续代码出现异常。
内容的提问来源于stack exchange,提问作者Newbie
相关产品推荐
相关产品推荐

