As we all know, “taxonomy” is a prominent feature provided by WordPress that we can allocate to a default post or custom post type. This feature is not available for the users. If you want to Create Taxonomy For a WordPress User, then this article is for you.
Prerequisites for this functionality
1) WordPress installed.
2) A theme where you can write the code in functions.php.
3) ACF plugin installed and activated.
If you have all the above, then let’s get started:
Step 1 – Register a Taxonomy
The first step is to register a taxonomy with any name. In our example, we will create a taxonomy with the name “user_category”. Add the following code to your active theme’s functions.php
file.
<?php
define( 'USER_CATEGORY_NAME', 'user_category' );
add_action( 'init', 'dcs_register_user_category_taxonomy' );
function dcs_register_user_category_taxonomy() {
register_taxonomy(
USER_CATEGORY_NAME,
'user',
array(
'public' => true,
'labels' => array(
'name'=> 'User Categories',
'singular_name'=> 'User Category',
'menu_name'=> 'User Categories',
'search_items'=> 'Search User Category',
'popular_items' => 'Popular User Categories',
'all_items'=> 'All User Categories',
'edit_item'=> 'Edit User Category',
'update_item'=> 'Update User Category',
'add_new_item'=> 'Add New User Category',
'new_item_name'=> 'New User Category Name',
),
'update_count_callback' => function() {
return;
}
)
);
}
?>
Step 2 – Add admin menu
Now we have to add an admin menu item under the user page using “add_users_page” hook. Add the following code to your active theme’s functions.php
file.
<?php
add_action( 'admin_menu', 'dcs_add_user_categories_admin_page' );
function dcs_add_user_categories_admin_page() {
$taxonomy = get_taxonomy( USER_CATEGORY_NAME );
add_users_page(
esc_attr( $taxonomy->labels->menu_name ),
esc_attr( $taxonomy->labels->menu_name ),
$taxonomy->cap->manage_terms,
'edit-tags.php?taxonomy=' . $taxonomy->name
);
}
Up to here, your taxonomy is ready for WordPress users, but the problem is that when we will add a term, then this will activate the post menu from the left.
To fix this issue, add the following code to your active theme’s functions.php
file.
<?php
add_filter( 'submenu_file', 'dcs_set_user_category_submenu_active' );
function dcs_set_user_category_submenu_active( $submenu_file ) {
global $parent_file;
if( 'edit-tags.php?taxonomy=' . USER_CATEGORY_NAME == $submenu_file ) {
$parent_file = 'users.php';
}
return $submenu_file;
}