WordPress如何用get_post_types()获取含已发布文章的类型并排除指定类型
get_post_types()函数的使用
实现目标:搜索页无匹配结果时,展示所有存在已发布文章的文章类型列表,同时支持按需排除指定文章类型,功能基于get_post_types()函数实现。
文章类型统计
| 文章类型 | 已发布文章数量 |
|---|---|
| one | 10 |
| two | 12 |
| three | 0 |
| four | 2 |
| five | 15 |
过滤规则:
- 过滤掉无已发布文章的类型,例如示例中
three已发布数量为0,不展示 - 支持手动指定排除类型,例如示例中
four虽有2篇已发布文章,仍需排除不展示
原生get_post_types()仅会按照传入的基础参数匹配文章类型,不会自动校验类型下的已发布文章数量,也没有内置指定类型排除逻辑,直接使用无法满足过滤需求。原有代码如下:
<?php $args = array( 'public' => true, '_builtin' => false, ); $output = 'names'; // 可选值 'names' 或 'objects',默认值为 'names' $operator = 'and'; // 可选值 'and' 或 'or',默认值为 'and' $post_types = get_post_types( $args, $output, $operator ); if ( ! empty ( $post_types ) ) { echo '<ul>'; foreach ( $post_types as $post_type ) { echo '<li>' . $post_type . '</li>'; } echo '<ul>'; // 此处存在标签闭合笔误,正确应为</ul> } ?>
修正后可直接使用的代码
<?php // 基础查询参数 $args = array( 'public' => true, '_builtin' => false, ); $output = 'names'; $operator = 'and'; // 手动配置需要排除的文章类型slug,按需增删数组内容即可 $exclude_types = array('four'); // 获取符合基础条件的所有文章类型 $post_types = get_post_types($args, $output, $operator); if ( ! empty($post_types) ) { echo '<ul>'; foreach ( $post_types as $type ) { // 命中手动排除列表则跳过 if ( in_array($type, $exclude_types) ) { continue; } // 统计当前类型已发布文章数量 $published_num = wp_count_posts($type)->publish; // 仅输出存在已发布文章的类型 if ( $published_num > 0 ) { echo '<li>' . esc_html($type) . ',已发布文章数:' . $published_num . '</li>'; } } echo '</ul>'; } ?>
代码说明:
- 排除逻辑通过独立数组配置,后续调整排除项不需要修改循环逻辑
- 用WordPress原生
wp_count_posts()函数统计各类型已发布内容数量,不需要手写数据库查询 - 输出时增加
esc_html()转义,避免特殊字符引发页面异常 - 修复了原代码中列表闭合标签写错的笔误
内容的提问来源于stack exchange,提问作者TutsInsider
相关产品推荐
相关产品推荐

