You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

WordPress多文章类型展示问题:需按类型分配4篇摘要展示数量

解决方案

没问题,我帮你调整代码来实现这个需求。核心思路是分三次独立查询:先拉取最新的1篇文章(不管类型)作为完整内容展示,然后分别获取2篇最新的post类型和2篇最新的tutorial类型文章(要排除已经显示的那篇完整文章,避免重复),最后依次输出这些内容。

以下是完整的实现代码:

<?php
// 1. 获取最新的1篇文章(不限类型),作为完整内容展示
$featured_args = array(
    'post_type' => array('post', 'tutorial'),
    'posts_per_page' => 1,
    'orderby' => 'date',
    'order' => 'DESC'
);
$featured_query = new WP_Query($featured_args);

$featured_post_id = 0; // 初始化变量,用于存储已展示文章的ID
if ($featured_query->have_posts()) :
    while ($featured_query->have_posts()) : $featured_query->the_post();
        $featured_post_id = get_the_ID(); // 记录当前文章ID,后续排除
        ?>
        <h2><?php the_title(); ?></h2>
        <?php the_content(); ?>
    <?php endwhile;
    wp_reset_postdata(); // 恢复全局$post变量,避免影响后续查询
endif;

// 2. 获取2篇最新的post类型文章(排除已展示的那篇)
$post_args = array(
    'post_type' => 'post',
    'posts_per_page' => 2,
    'orderby' => 'date',
    'order' => 'DESC',
    'post__not_in' => array($featured_post_id) // 排除已显示的文章
);
$post_query = new WP_Query($post_args);

if ($post_query->have_posts()) :
    while ($post_query->have_posts()) : $post_query->the_post();
        ?>
        <h2><?php the_title(); ?></h2>
        <?php the_excerpt(); ?>
    <?php endwhile;
    wp_reset_postdata();
endif;

// 3. 获取2篇最新的tutorial类型文章(排除已展示的那篇)
$tutorial_args = array(
    'post_type' => 'tutorial',
    'posts_per_page' => 2,
    'orderby' => 'date',
    'order' => 'DESC',
    'post__not_in' => array($featured_post_id) // 排除已显示的文章
);
$tutorial_query = new WP_Query($tutorial_args);

if ($tutorial_query->have_posts()) :
    while ($tutorial_query->have_posts()) : $tutorial_query->the_post();
        ?>
        <h2><?php the_title(); ?></h2>
        <?php the_excerpt(); ?>
    <?php endwhile;
    wp_reset_postdata();
endif;
?>

关键说明:

  • 排除重复内容:使用post__not_in参数,把已经作为完整内容展示的文章ID传入,确保后续的摘要列表不会重复显示这篇文章。
  • 独立查询控制:分三次查询分别获取不同类型的内容,精准控制每种类型展示的数量(2篇post、2篇tutorial)。
  • 全局变量恢复:每个WP_Query循环结束后调用wp_reset_postdata(),保证后续的WordPress模板标签(如the_title()、the_excerpt())能正常工作,避免变量污染。

内容的提问来源于stack exchange,提问作者hbrovell

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.13 07:21:36