📅  最后修改于: 2023-12-03 15:21:15.259000             🧑  作者: Mango
在 WordPress 中,我们可以使用注册自定义帖子类型来创建各种不同的内容类型。该功能允许开发者注册新的帖子类型,为 WordPress 建立自定义帖子类型。在这篇文章中,我们将介绍 WP 注册帖子类型支持的使用方法。
要注册自定义帖子类型,我们需要使用 register_post_type()
函数。例如,以下代码将注册一个名为“book”的前缀的帖子类型:
add_action( 'init', 'register_book_post_type' );
function register_book_post_type() {
$args = array(
'public' => true,
'label' => 'Books',
);
register_post_type( 'book', $args );
}
在上面的代码中,我们首先使用 add_action()
将 register_book_post_type()
函数添加到“init”挂钩中。然后我们定义了一个名为 $args
的数组作为 register_post_type()
函数的第二个参数。该数组中有两个元素:public
和 label
。public
表示是否允许公共查看该帖子类型,label
表示在 WordPress 后台管理界面中的名称。
我们可以使用 register_post_type()
函数中的参数来定义自定义帖子类型的所有内容。以下是一些重要的参数:
public
:定义该帖子类型是否可见于公众。label
:在 WordPress 管理面板中显示的名称。menu_icon
:定义菜单项左侧显示的图标。supports
:定义支持的功能,包括缩略图、自定义字段、编辑器等。rewrite
:可在 WordPress 和自定义帖子类型之间定义链接结构。taxonomies
:定义帖子类型的类别分类法和标签分类法。capability_type
:定义什么权限对应于该帖子类型。更多关于 register_post_type()
函数的参数可以查看官方文档。
以下是一份具体的代码示例,其中我们定义了一个名为“product”的帖子类型,支持文章、自定义字段和缩略图。该帖子类型还将包含类别分类法和标签分类法。
add_action( 'init', 'register_product_post_type' );
function register_product_post_type() {
$labels = array(
'name' => _x( 'Products', 'post type general name', 'my-theme' ),
'singular_name' => _x( 'Product', 'post type singular name', 'my-theme' ),
'menu_name' => _x( 'Products', 'admin menu', 'my-theme' ),
'name_admin_bar' => _x( 'Product', 'add new on admin bar', 'my-theme' ),
'add_new' => _x( 'Add New', 'product', 'my-theme' ),
'add_new_item' => __( 'Add New Product', 'my-theme' ),
'new_item' => __( 'New Product', 'my-theme' ),
'edit_item' => __( 'Edit Product', 'my-theme' ),
'view_item' => __( 'View Product', 'my-theme' ),
'all_items' => __( 'All Products', 'my-theme' ),
'search_items' => __( 'Search Products', 'my-theme' ),
'parent_item_colon' => __( 'Parent Products:', 'my-theme' ),
'not_found' => __( 'No products found.', 'my-theme' ),
'not_found_in_trash' => __( 'No products found in Trash.', 'my-theme' ),
);
$args = array(
'labels' => $labels,
'description' => __( 'Description.', 'my-theme' ),
'taxonomies' => array( 'category', 'post_tag' ),
'public' => true,
'menu_icon' => 'dashicons-cart',
'show_ui' => true,
'show_in_menu' => true,
'menu_position' => 5,
'supports' => array( 'title', 'editor', 'thumbnail', 'custom-fields' ),
'has_archive' => true,
'rewrite' => array( 'slug' => 'products' ),
'capability_type' => 'post',
'hierarchical' => false,
);
register_post_type( 'product', $args );
}
通过上面的例子,我们可以清楚地看到如何使用 register_post_type()
函数在 WordPress 中注册自定义帖子类型。注册自定义帖子类型,可以帮助我们更好地针对特定的内容类型进行管理和展示。