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

WordPress如何判断查询是否有文章 自定义WooCommerce无文章提示

修改后的完整代码如下:

add_action( 'woocommerce_account_dashboard' , 'recent_posts', 3 );
function recent_posts() {
    if ( is_user_logged_in() ):
        global $current_user;
        wp_get_current_user();
        $author_query = array(
            'posts_per_page' => '-1',
            'author' => $current_user->ID
        );
        $author_posts = new WP_Query($author_query);
        ?>
        <div id="recentposts">
        <?php if ( $author_posts->have_posts() ) : ?>
            <ul class="liststylenone">
            <?php
            while($author_posts->have_posts()) : $author_posts->the_post();
            ?>
                <li><a href="<?php the_permalink(); ?>" title="<?php the_title_attribute(); ?>"><?php the_title(); ?></a></li>   
            <?php           
            endwhile;
            ?>
            </ul>
            <?php wp_reset_postdata(); // 重置查询,避免后续内容异常 ?>
        <?php else : ?>
            <p>no articles</p>
        <?php endif; ?>
        </div>
    <?php
    else :
        echo "not logged in";
    endif;
}

核心调整说明

  • 在文章列表渲染前新增了$author_posts->have_posts()判断,查询到当前用户有发布的文章时才渲染列表,没有匹配结果时直接输出no articles提示
  • 新增了wp_reset_postdata()调用,修复原生代码可能导致的后续全局查询错乱问题

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 05:18:00