W e b I n s i g h t s .

WordPress帳號分類教學

WordPress帳號分類教學

最近,我們需要進行一個把使用者指定給不同分類的專案,WordPress本身並不支援這個功能。不過,我們知道WordPress大神可以幫你完成你的願望,而且不需要花費太多的功夫。

新增自定義分類(Register Taxonomy)

首先,我們都知道在使用自定義分類之前要先新增一個才行,在這裡也一樣。我們先來新增一個叫做User Category的自定義分類。
function register_user_taxonomy(){

$labels = array(
‘name’ => ‘User Category’,
‘singular_name’ => ‘User Category’,
‘search_items’ => ‘Search User Categories’,
‘all_items’ => ‘All User Categories’,
‘parent_item’ => ‘Parent User Category’,
‘parent_item_colon’ => ‘Parent User Category’,
‘edit_item’ => ‘Edit User Category’,
‘update_item’ => ‘Update User Category’,
‘add_new_item’ => ‘Add New User Category’,
‘new_item_name’ => ‘New User Category Name’,
‘menu_name’ => ‘User Category’
);

$args = array(
‘hierarchical’ => true,
‘labels’ => $labels,
‘show_ui’ => true,
‘show_admin_column’ => true,
‘query_var’ => true,
‘rewrite’ => array( ‘slug’ => ‘user_category’)
);

register_taxonomy( ‘user_category’ , ‘user’ , $args );
}
add_action( ‘init’, ‘register_user_taxonomy’ );
請注意,我們指定user為物件類型。

新增自定義分類編輯子頁面

現在我們已經新增好了我們的自定義分類,但是我們在後台管理介面找不到它,這是為什麼呢?因為我們使用user為物件類型,但是我們並沒有稱為user的文章類型。

我們能做的就是在帳號管理頁增加一個子頁面,管理員(admin)才能夠編輯使用者分類,以下是我們的做法。
function add_user_category_menu() {
add_submenu_page( 'users.php' , 'User Category', 'User Category' , 'add_users', 'edit-tags.php?taxonomy=user_category' );
}
add_action( 'admin_menu', 'add_user_category_menu' );

現在我們可以看到分類項目出現在帳號管理頁

User-Category
User-Category-Edit

在個人資訊頁增加我們的帳號分類

一旦我們創建了自訂分類名稱,我們會想要把它指定給我們的帳號。我們需要把它顯示在個人資訊頁,這樣使用者/管理員可以把分類名稱指定給他們。以下是程式範例:
add_action( 'show_user_profile', 'show_user_category' );
add_action( 'edit_user_profile', 'show_user_category' );
function show_user_category( $user ) {

//get the terms that the user is assigned to
$assigned_terms = wp_get_object_terms( $user->ID, ‘user_category’ );
$assigned_term_ids = array();
foreach( $assigned_terms as $term ) {
$assigned_term_ids[] = $term->term_id;
}

//get all the terms we have
$user_cats = get_terms( ‘user_category’, array(‘hide_empty’=>false) );

echo ”

User Category

“;

//list the terms as checkbox, make sure the assigned terms are checked
foreach( $user_cats as $cat ) { ?>
term_id.'”>’.$cat->name.’‘;
echo ‘
‘;
}
}

儲存帳號分類

還想再看下去嗎?別擔心,這已經是最後一步了!我們當然想要在帳號頁儲存我們的帳號分類/分類名稱,其實還滿簡單的
add_action( 'personal_options_update', 'save_user_category' );
add_action( 'edit_user_profile_update', 'save_user_category' );
function save_user_category( $user_id) {

$user_terms = $_POST[‘user_category’];
$terms = array_unique( array_map(‘intval’, $user_terms) );
wp_set_object_terms( $user_id, $terms, ‘user_category’, false );

//make sure you clear the term cache
clean_object_term_cache( $user_id, ‘user_category’ );
}
這樣就大功告成了,但是你可能會想說:應該會有外掛有類似的功能吧!?

其實還真的有,看看這個吧=> http://wordpress.org/plugins/user-taxonomies/

文章最後更新於 : 2019/07/19