WordPress有五种默认的文章类型:post
、page
、attachment
、revision
和menu
。
在开发插件时,您可能需要创建自己的特定内容类型:例如,电子商务网站的产品、电子学习网站的作业或评论网站的电影。
使用自定义文章类型,您可以注册自己的文章类型。注册自定义文章类型后,它将获得一个新的顶级管理界面,可用于管理和创建该类型的文章。
要注册新的文章类型,可以使用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()的参考页。
Warning:您必须在admin_init
钩子之前和after_setup_theme
钩子之后调用register_post_type()
。很适合的一个钩子是init
动作钩子。
命名最佳实践
重要的是,在文章类型函数和标识符前面加一个与插件、主题或网站相对应的短前缀。
Warning:确保自定义文章类型标识符不超过20个字符,因为数据库中的post_type
列当前是该长度的VARCHAR字段。
Warning:为了确保前向兼容性,不要使用 wp_ 作为您的标识符 - WordPress核心正在使用它。
Warning:如果您的标识符太通用(例如:“product
”),它可能会与选择使用相同标识符的其他插件或主题冲突。
Note:如果不禁用其中一个冲突的文章类型,则不可能解决重复的文章类型标识符。
URL
自定义文章类型在站点URL结构中有它自己的slug。
默认情况下,wporg_product
类型的文章将使用以下URL结构:http://example.com/wporg_product/%product_name%
。
wporg_product
是自定义文章类型的slug,%product_name%
是特定产品(属于该类型的文章)的slug(即post_name)。
最终的固定链接形似:http://example.com/wporg_product/wporg-is-awesome
。
您可以在编辑界面上看到自定义文章类型的固定链接,就像默认文章类型一样。
自定义文章类型的自定义Slug
要为自定义文章类型设置自定义slug,只需添加一个键=>值对到register_post_type()
参数数组中的rewrite
键。
例子:
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%
Warning:使用像products
这样的通用slug可能会与其他插件或主题发生冲突,因此请尝试使用更具体内容。
Note:与自定义文章类型标识符不同,通过更改冲突文章类型之一的slug,可以轻松解决重复slug问题。
如果插件作者包含对参数的apply_filters()
调用,则可以通过编程方式重写通过register_post_type()
函数提交的参数来完成。