WP DEVELOP

EP029. “让 Event 支持模块编辑器(show_in_rest)”

首页 WordPress 开发课程 CUSTOM POST TYPE 入门 · EP029
约 6 分钟· #EP029#CUSTOM POST TYPE 入门
🔒 登录后可标记已读

这是一篇很短的图文讲座,只做一件事:给上一讲注册的 event 文章类型加一个 show_in_rest => true。不加这一行,自定义文章类型默认会用旧版 Classic Editor,而不是现代的 Block Editor(区块编辑器),因为 Block Editor 几乎完全靠 JavaScript 驱动,要通过 REST API 去抓取文章数据,所以文章类型必须先在 REST API 里「可见」,Block Editor 才能用。REST API 具体是什么,后面章节会详细讲,这里先知道这一行的作用就够了。

涉及文件

  • wp-content/mu-plugins/university-post-types.php (修改)

代码实现

// wp-content/mu-plugins/university-post-types.php

function university_post_types() {
  register_post_type('event', array(
    'public' => true,
    'show_in_rest' => true, // 新增:让 event 支持 REST API,从而能用新版 Block Editor
    'labels' => array(
      'name' => 'Events',
      'add_new_item' => 'Add New Event',
      'edit_item' => 'Edit Event',
      'all_items' => 'All Events',
      'singular_name' => 'Event'
    ),
    'menu_icon' => 'dashicons-calendar'
  ));
}

add_action('init', 'university_post_types');

只加了 show_in_rest => true 这一行(顺序不影响功能,加在数组任意位置都行)。

[截图:wp-admin 后台新建 Event 的编辑画面,已经是新版 Block Editor 界面而不是旧版 Classic Editor]

Hook / Function 速查

名称类型用途
show_in_restregister_post_type() 参数设为 true 让该文章类型开放给 REST API,是新版 Block Editor 能正常工作的前提条件

常见坑

  • 不加 show_in_rest,自定义文章类型的编辑画面会退回旧版 Classic Editor,而不是 Block Editor。
  • 原文提醒:如果之后在 supports 参数里手动列出要支持的功能,只要没有显式包含 editor,也会导致退回 Classic Editor —— 但如果压根不写 supports 这个参数,则默认会用 Block Editor。这一点在这一讲就先埋个伏笔,supports 参数要到 EP031 才会真正加上。

延伸 / 后续讲座会用到

EP030 会继续在这个文件里加 has_archiverewrite 参数,让 event 有归档页面。EP031 会加 supports 参数(含 excerpt),到时候要记得同时显式列出 editor,否则会退回 Classic Editor。

Sources

Udemy:

  • Become a WordPress Developer: Unlocking Power With Code — Section 7, EP029