如何检查WP_Query查询结果中是否存在指定自定义post_type文章?
问题原因
你之前使用的wp_posts_count()默认查询全站对应post_type的文章总数,没有携带当前分类法的筛选条件,因此无法得到当前分类下的统计结果。
解决方法
分两种场景实现:
场景1:仅判断当前分页的查询结果中是否存在对应post_type
不需要额外查询数据库,直接遍历已获取的查询结果判断即可,性能最优:
// 在你调用query_posts之后、输出菜单之前加入以下代码 $has_song = false; $has_dance = false; foreach ( $wp_query->posts as $post ) { if ( $post->post_type === 'song' ) $has_song = true; if ( $post->post_type === 'dance' ) $has_dance = true; // 两种类型都找到就提前终止循环,减少性能消耗 if ( $has_song && $has_dance ) break; } // 输出对应提示文本 if ( $has_song && $has_dance ) { echo '该分类法包含Song、Dance类文章'; } elseif ( $has_song ) { echo '该分类法仅包含Song类文章'; } elseif ( $has_dance ) { echo '该分类法仅包含Dance类文章'; } else { echo '该分类法下暂无相关文章'; }
场景2:需要判断当前分类法下所有分页是否存在对应post_type
需要新增带分类筛选条件的查询,统计全部分类下的对应post_type数量:
// 获取当前分类法的term信息 $current_term = get_queried_object(); $tax_query = array( array( 'taxonomy' => $current_term->taxonomy, 'field' => 'term_id', 'terms' => $current_term->term_id, ) ); // 统计当前分类下song的总数量 $song_count = get_posts( array( 'post_type' => 'song', 'post_status' => 'publish', 'posts_per_page' => -1, 'fields' => 'ids', 'tax_query' => $tax_query, ) ); $song_count = count( $song_count ); // 统计当前分类下dance的总数量 $dance_count = get_posts( array( 'post_type' => 'dance', 'post_status' => 'publish', 'posts_per_page' => -1, 'fields' => 'ids', 'tax_query' => $tax_query, ) ); $dance_count = count( $dance_count ); // 输出对应提示文本 if ( $song_count > 0 && $dance_count > 0 ) { echo '该分类法包含Song、Dance类文章'; } elseif ( $song_count > 0 ) { echo '该分类法仅包含Song类文章'; } elseif ( $dance_count > 0 ) { echo '该分类法仅包含Dance类文章'; } else { echo '该分类法下暂无相关文章'; }
额外注意
不推荐使用query_posts()修改主查询,容易引发全局变量冲突,建议使用pre_get_posts钩子修改默认主查询,或者用WP_Query生成自定义查询。
内容的提问来源于stack exchange,提问作者theKing
相关产品推荐
相关产品推荐

