WordPress创建自定义内容类型
WordPress的数据非常简单,但是设计的非常不错,所以可以很灵活的扩展网站的内容,可以通过register_post_type很方便的创建自定义内容类型:
function yxseo_register_product() {
$labels = array(
'name' => __('产品', 'yxseo'),
'singular_name' => '产品',
'add_new' => '添加产品',
'add_new_item' => '添加新产品',
'edit_item' => '编辑产品',
'new_item' => '写产品',
'view_item' => '查看产品',
'view_items' => '查看产品',
'search_items' => '搜索产品',
'not_found' => '未找到产品。',
'not_found_in_trash' => '回收站中没有产品。',
'parent_item_colon' => '',
'all_items' => '所有产品',
'archives' => '产品归档',
'attributes' => '产品属性',
'insert_into_item' => '插入至产品',
'uploaded_to_this_item' => '上传到本产品的',
'featured_image' => '产品默认图片',
'set_featured_image' => '设置默认图片',
'remove_featured_image' => '移除默认图片',
'use_featured_image' => '设置为默认图片',
'filter_items_list' => '筛选产品列表',
'filter_by_date' => '按日期筛选',
'items_list_navigation' => '产品列表导航',
'items_list' => '产品列表',
'item_published' => '产品已发布。',
'item_published_privately' => '产品已私密发布。',
'item_reverted_to_draft' => '产品已恢复为草稿。',
'item_scheduled' => '产品已排入发布计划。',
'item_updated' => '产品已更新。',
'item_link' => '产品链接',
'item_link_description' => '目标产品的链接。',
'menu_name' => '产品',
'name_admin_bar' => '产品'
);
$args = array(
'labels' => $labels,
'menu_icon' => 'dashicons-screenoptions',
'menu_position' => 5,
'public' => true,
'publicly_queryable' => true,
'show_ui' => true,
'show_in_menu' => true,
'query_var' => true,
'rewrite' => array( 'slug' => 'products' ),
'capability_type' => 'post',
'has_archive' => true,
'hierarchical' => false,
'show_in_rest' => true,
'supports' => array( 'title', 'editor', 'author', 'thumbnail', 'excerpt', 'comments' ),
);
register_post_type( 'product', $args );
}
add_action( 'init', 'yxseo_register_product' );
$labels是用来显示提示文本,在后台不需要多语言的情况下,我们只需要把$label->name做一下可翻译文本即可(因为前台归档页面可能会调用此翻译)。
$args参数有很多,具体可以参考(register_post_type() | Function | WordPress Developer Resources)
比较重要的几个是:
- public:这个决定这个内容类型在后台显示与否,大多数情况下是true,但是有一些插件会创建一些不可见的内容类型。
- hierarchical:是否以层级显示,可以参考一下自带的page模型。
- show_in_rest:如果需要启用古腾堡编辑器,那必须为true。
- supports:此内容类型所显示的字段。
最后,用钩子在挂载到wordpress的init函数中。
发表回复