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

WordPress如何获取全部自定义及内置post type slug?代码返回空问题排查

问题原因

你调用get_post_types查询自定义文章类型返回空数组的核心原因是执行时机错误:

  • WordPress 内置文章类型(post、page、attachment等)的注册时机极早,在初始化流程早期就完成写入全局配置,所以你提前调用无参数的get_post_types()也能正常返回内置结果。
  • 第三方插件注册的自定义文章类型(比如WooCommerce的product、LearnDash的course)、你自己开发的自定义文章类型,默认都是挂载在init钩子(优先级10)上完成注册的,如果你在init钩子触发前、或是init钩子优先级低于10的函数中调用查询方法,此时自定义文章类型还未被注册到WordPress全局,自然查不到符合_builtin=false条件的结果。
正确实现方案

将你的查询逻辑挂载到init钩子,且设置优先级≥10,确保所有文章类型都完成注册后再执行查询即可,代码示例如下:

// 挂载到init钩子,优先级20,晚于绝大多数插件的文章类型注册逻辑
add_action('init', function () {
    // 需求1:获取所有(内置+自定义)post type slug
    $all_post_type_slugs = get_post_types([], 'names');

    // 需求2:仅获取所有公开的post type slug(内置+自定义)
    // $public_post_type_slugs = get_post_types(['public' => true], 'names');

    // 需求3:仅获取非内置的公开自定义post type slug
    // $custom_public_slugs = get_post_types(['public' => true, '_builtin' => false], 'names');

    // 打印结果
    echo "<pre>";
    print_r($all_post_type_slugs);
    echo "</pre>";
}, 20);

如果仅需要筛选特定属性的post type,调整get_post_types的第一个参数数组即可,不需要修改其他逻辑。

内容的提问来源于stack exchange,提问作者Parthavi Patel

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 14:36:05