WordPress自定义文章类型也就是PostType,是一个非常强大的功能,在开发WordPress主题的时候很常用到,例如:网址导航,那么该如何创建一个新的自定义文章类型(PostType)呢?下面有个主题给大家介绍下。
创建PostType
首先我们创建一个新的 PostType,这需要使用到 register_post_type 函数。
第一步:在你主题的 functions.php 文件下调用该函数:
register_post_type( $post_type, $args );
//$post_type 参数就是你自定义 Post Type 的名称。
function my_custom_post_product() {
$args = array();
register_post_type( 'product', $args );
}
add_action( 'init', 'my_custom_post_product' );
register_post_type 函数的参数很多,下面只列出比较常用的参数:
function my_custom_post_site() {
$labels = array(
'name' => _x( '网址导航', 'post type 名称' ),
'singular_name' => _x( '网址', 'post type 单个 item 时的名称,因为英文有复数' ),
'add_new' => _x( '新建网址', '添加新内容的链接名称' ),
'add_new_item' => __( '新建网址' ),
'edit_item' => __( '编辑网址' ),
'new_item' => __( '新网址' ),
'all_items' => __( '所有网址' ),
'view_item' => __( '查看网址' ),
'search_items' => __( '搜索网址' ),
'not_found' => __( '没有找到有关网址' ),
'not_found_in_trash' => __( '回收站里面没有相关网址' ),
'parent_item_colon' => '',
'menu_name' => '网址'
);
$args = array(
'labels' => $labels,
'description' => '网址信息',
'public' => true,
'menu_position' => 5,
'supports' => array( 'title', 'editor', 'thumbnail', 'excerpt', 'comments' ),
'has_archive' => true
);
register_post_type( 'site', $args );
}
add_action( 'init', 'my_custom_post_site' );
将上面代码加到主题 functions.php
的最下面,进入后台你会发现多出了 site
选项,如下图所示,这样表示注册成功:

注册成功后,接下来我们可以尝试在新建的 site
发表一篇网址类型的文章。
但是你会发现这样发表的自定义文章类型与默认文章类型基本相同,所以我们需要更多的自定义来完善我们的 site
类型。
下一篇文章我们继续讲解WordPress给自定义文章类型添加自定义分类法。