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
相关产品推荐
相关产品推荐

