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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | 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.
1 2 3 4 5 6 7 8 9 10 | 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.
1 2 3 4 5 6 7 8 | 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; } |