在WordPress中,使用register_taxonomy()
函数创建自定义分类法(taxonomy)是一个相对直接的过程。以下是创建自定义分类法的基本步骤:
-
定义钩子:首先,你需要确定在哪个钩子(hook)上注册你的自定义分类法。通常,
init
钩子是最佳选择,因为它在WordPress初始化过程中执行。 -
编写代码:在你的插件文件中,使用
add_action()
函数将你的自定义函数绑定到init
钩子上。 -
注册分类法:在自定义函数内部,使用
register_taxonomy()
函数来创建分类法。
以下是一个示例代码,展示了如何创建一个名为“Genre”的自定义分类法,并将其关联到“book”自定义文章类型(custom post type)。
function create_custom_taxonomy() {
// 设置标签,用于定义分类法
$labels = array(
'name' => _x( 'Genres', 'taxonomy general name' ),
'singular_name' => _x( 'Genre', 'taxonomy singular name' ),
'search_items' => __( 'Search Genres' ),
'all_items' => __( 'All Genres' ),
'parent_item' => __( 'Parent Genre' ),
'parent_item_colon' => __( 'Parent Genre:' ),
'edit_item' => __( 'Edit Genre' ),
'update_item' => __( 'Update Genre' ),
'add_new_item' => __( 'Add New Genre' ),
'new_item_name' => __( 'New Genre Name' ),
'menu_name' => __( 'Genres' ),
);
// 设置参数
$args = array(
'hierarchical' => true, // 是否有层级关系,类似分类目录
'labels' => $labels,
'show_ui' => true,
'show_admin_column' => true,
'query_var' => true,
'rewrite' => array( 'slug' => 'genre' ),
);
// 注册分类法
register_taxonomy('genre', array('book'), $args);
}
// 将自定义函数绑定到init钩子
add_action('init', 'create_custom_taxonomy', 0);
在这个例子中,我们首先定义了分类法的标签和参数。然后,我们使用register_taxonomy()
函数注册了一个名为“genre”的分类法,并将其与“book”文章类型关联。最后,我们使用add_action()
函数将create_custom_taxonomy
函数绑定到init
钩子上。
确保在执行此代码之前,你的“book”自定义文章类型已经被注册。如果你还没有注册自定义文章类型,你需要在同一个插件或主题的函数文件中先注册它。