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

自定义文章类型无文章时显示自定义消息问题求助

问题解决:WordPress分类下无文章时显示自定义提示

你需要在查询判断中添加else分支来处理无文章的情况,同时记得重置查询以避免影响后续内容。以下是具体的修改方案:

原代码问题

现有代码仅处理了有文章的场景,未对have_posts()返回false的情况做逻辑处理,所以无法触发自定义提示。

修改后的完整代码

<div class="industry_item_grid">
        <div class="industry_item_head">
            <h3 class="industry_title">Telecom</h3>
            <a href="<?php echo site_url(
                "/category/telecom"
            ); ?>" class="casestudy_viewall">View all</a>
        </div>
        <div class="industry_item_row">
            <?php
            $paged = get_query_var("paged")
                ? get_query_var("paged")
                : 1;
            $args = [
                "post_type" => "post",
                "post_status" => "publish",
                "category_name" => "Telecom",
                "posts_per_page" => 3,
                "cat" => 23,
                "paged" => $paged,
            ];
            $arr_posts = new WP_Query($args);
            $totalpost = $arr_posts->found_posts;

            if ($arr_posts->have_posts()):
                while ($arr_posts->have_posts()):
                    $arr_posts->the_post(); ?>
                    <?php the_content(); // 取消注释以输出文章内容 ?>
            <?php
                endwhile;
                wp_reset_postdata(); // 重置查询,恢复全局post对象
            else:
                // 无文章时显示自定义提示
                echo '<p class="no-posts-message">抱歉,暂无可用文章</p>';
            endif;
            ?>
        </div>
</div>

关键修改说明

  • 新增else分支:当查询不到文章时,直接输出自定义提示文本,可通过添加CSS类no-posts-message来美化样式
  • 添加wp_reset_postdata():使用自定义WP_Query后必须调用该函数,避免后续模板中的全局查询(如the_post())出现异常
  • 取消//the_content();注释:确保有文章时能正常输出内容(若不需要显示文章内容可重新注释)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.30 21:15:42