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

无法获取WordPress分类noticeboard下的文章,请求排查代码问题

排查WP_Query无法获取noticeboard分类文章的问题

我来帮你捋捋这个问题——明明分类下有文章,但代码就是拿不到结果,大概率是这几个细节没做好,咱们逐个排查:

1. 确认分类别名(Slug)是否正确

你用的category_name参数要求的是分类的别名(slug),而不是后台显示的分类名称。比如如果你的分类显示名是“公告栏”,但别名设置的是announcement-board,那用'category_name' => 'noticeboard'肯定查不到。

你可以去后台「文章」→「分类」,点击对应分类查看别名是否确实是noticeboard。如果怕搞混,更稳妥的方式是用分类ID来查询,替换category_name为cat参数:

$args = array(
    'cat' => 123, // 替换成你的noticeboard分类ID
    'nopaging'=>true,
    'posts_per_page'=>5
);

2. 检查文章是否设置了特色图片

你的代码里只有当文章满足has_post_thumbnail()为真时,才会把文章数据加入$posts数组。如果那篇分类下的文章没有设置特色图片,就会被过滤掉,前端自然看不到内容。

你可以先注释掉这个判断,测试是否能获取到文章:

// if(has_post_thumbnail()){
    $temp = array();
    $temp['title'] = get_the_title();
    $temp['excerpt'] = get_excerpt(80);
    $temp['url'] = get_the_permalink();
    $posts[] = $temp;
// }

如果这样能显示文章,说明是特色图片的问题——要么给文章补上特色图,要么去掉这个条件判断。

3. 确认文章的发布状态

WP_Query默认只会查询post_status为publish的文章。如果那篇文章是草稿、私密或待审核状态,也不会被纳入查询结果。你可以在参数里明确指定要包含的状态:

$args = array(
    'category_name' => 'noticeboard',
    'nopaging'=>true,
    'posts_per_page'=>5,
    'post_status' => array('publish', 'draft') // 根据需求添加状态
);

4. 排查自定义get_excerpt函数的问题

虽然可能性相对小,但如果你的get_excerpt函数存在错误(比如抛出异常),可能会导致循环中断,无法收集文章数据。你可以先用WordPress原生函数替代测试:

$temp['excerpt'] = wp_trim_words(get_the_excerpt(), 80); // 原生函数截取80字摘要

5. 清除WordPress缓存

有时候缓存会导致查询结果不更新,你可以试试清除网站的缓存插件(如果有),或者刷新后台「设置」→「固定链接」页面,重新生成permalink规则,这往往能解决一些奇怪的查询问题。

修复后的参考代码

这里给你一个去掉特色图判断、用分类ID查询的版本,确保能先获取到文章:

<?php 
//Noticeboard Posts 
$posts = array(); 
$args = array( 
    'cat' => 123, // 替换为你的noticeboard分类ID
    'nopaging'=>true, 
    'posts_per_page'=>5,
    'post_status' => 'publish'
); 
$posts_query = new WP_Query( $args ); 

if ( $posts_query->have_posts() ) { 
    while ( $posts_query->have_posts() ) { 
        $posts_query->the_post(); 
        $temp = array(); 
        $temp['title'] = get_the_title(); 
        $temp['excerpt'] = wp_trim_words(get_the_excerpt(), 80); // 用原生函数替代自定义
        $temp['url'] = get_the_permalink(); 
        $posts[] = $temp; 
    } 
} 
wp_reset_postdata(); 

//Content List 
foreach($posts as $post){ 
    extract($post); 
?> 
<div class="noticeboard-element"> 
    <h5><?php echo $title ?></h5> 
    <div><?php echo $excerpt; ?><a href="<?php echo $url; ?>" class="float-right"><u>Read More</u></a></div> 
    <svg height="1" width="100%"> 
        <line x1="25%" y1="0" x2="75%" y2="0" style="stroke:rgb(255,255,255);stroke-width:2" /> 
    </svg> 
</div> 
<?php } ?>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.14 09:10:55