WordPress 自带五种默认文章类型:post、page、attachment、revision 和 menu。
在开发插件时,您可能需要创建特定的内容类型:例如电商网站的产品、在线学习网站的作业或评论网站的电影。
使用自定义文章类型(Custom Post Types),您可以注册自己的文章类型。一旦注册了自定义文章类型,就会获得一个新的顶级管理屏幕,可用于管理和创建该类型的文章。
要注册新的文章类型,请使用 register_post_type() 函数。
我们建议您将自定义文章类型放在插件中而不是主题中。这样可以确保即使用户更改了主题,用户内容仍然保持可移植性。
以下示例注册了一个新的文章类型 Products,该类型在数据库中标识为 wporg_product。
function wporg_custom_post_type() {
register_post_type('wporg_product',
array(
'labels' => array(
'name' => __('Products', 'textdomain'),
'singular_name' => __('Product', 'textdomain'),
),
'public' => true,
'has_archive' => true,
)
);
}
add_action('init', 'wporg_custom_post_type');
请访问 register_post_type() 的参考页面以了解参数描述。
您必须在 admin_init 钩子之前调用 register_post_type(),并在 after_setup_theme 钩子之后调用。建议使用 init 操作钩子。
命名最佳实践
重要的是,您应以对应于您的插件、主题或网站的简短前缀来前缀文章类型函数和标识符。
确保您的自定义文章类型标识符不超过 20 个字符,因为数据库中的 post_type 列当前是长度为该长度的 VARCHAR 字段。
为了确保向前兼容性,不要使用 wp_ 作为标识符——它正被 WordPress 核心使用。
如果您的标识符过于通用(例如:product),它可能会与其他选择使用该相同标识符的插件或主题发生冲突。
解决重复文章类型标识符的问题需要在禁用其中一个冲突的文章类型的情况下才能完成。
URL
自定义文章类型会在站点 URL 结构中获得自己的 slug。
类型为 wporg_product 的文章默认将使用以下 URL 结构:http://example.com/wporg_product/%product_name%。
wporg_product 是您的自定义文章类型的 slug,%product_name% 是您特定产品的 slug。
最终的永久链接将是:http://example.com/wporg_product/wporg-is-awesome。
您可以在自定义文章类型的编辑屏幕上看到永久链接,就像默认文章类型一样。
为自定义文章类型设置自定义 slug
要为您的自定义文章类型的 slug 设置自定义 slug,您只需在 register_post_type() 参数数组中的 rewrite 键中添加一个 key => value 对。
示例:
function wporg_custom_post_type() {
register_post_type('wporg_product',
array(
'labels' => array(
'name' => __( 'Products', 'textdomain' ),
'singular_name' => __( 'Product', 'textdomain' ),
),
'public' => true,
'has_archive' => true,
'rewrite' => array( 'slug' => 'products' ), // my custom slug
)
);
}
add_action('init', 'wporg_custom_post_type');
上述代码将产生以下 URL 结构:http://example.com/products/%product_name%
使用像 products 这样的通用 slug 可能会与其他插件或主题发生冲突,因此请尝试使用更具体于您内容的 slug。
与自定义文章类型标识符不同,重复 slug 问题可以通过更改其中一个冲突文章类型的 slug 轻松解决。
如果插件作者在参数中包含了 apply_filters() 调用,则可以通过覆盖通过 register_post_type() 函数提交的参数来以编程方式完成此操作。