WordPress 自定义文章类型:register_post_type 的 6 个必填细节

· wordpress · 阅读 10
摘要

register_post_type() 参数有二十多个,能跑起来只需要几个,但要跑得对,下面这几项不能省。1. labels不写 labels,后台菜单会显示成“文章”加复数形式,用户看不懂。至少要给出 name、singular_nam

register_post_type() 参数有二十多个,能跑起来只需要几个,但要跑得对,下面这几项不能省。

1. labels

不写 labels,后台菜单会显示成“文章”加复数形式,用户看不懂。至少要给出 name、singular_name、add_new_item。

2. public 与 has_archive

'public' => true,
'has_archive' => true,
'rewrite' => ['slug' => 'portfolio', 'with_front' => false],

public=true 才有了前台路由和后台菜单;has_archive 决定有没有列表页。少写 with_front,固定链接前缀会被带进新类型的 URL 里,路径变得很难看。

3. supports

不声明的话,编辑器里连标题框都没有。常用组合:['title','editor','thumbnail','excerpt']。

4. show_in_rest

想让古腾堡编辑器正常工作、或者要用 REST API 和区块主题,必须设 true。老教程里经常漏掉这一条,结果编辑器退化成经典模式。

5. 注册时机

必须挂在 init 上,优先级默认 10 即可。不要在 after_setup_theme 里注册,那时机太早,部分 API 未就绪。

6. 刷新固定链接

新类型注册后,前台 404 是最高频的投诉。原因是 rewrite 规则没刷新。解决办法是在激活钩子里调用 flush_rewrite_rules(),卸载时再调一次清掉。

register_activation_hook(__FILE__, function(){
    mfp_register_portfolio();
    flush_rewrite_rules();
});