はじめに
WordPressサイトを運営していると、投稿者ごとに使用できるカテゴリーやタグをあらかじめ決めておきたい場合があります。
入力ミスを防止するために、ユーザーごとにカテゴリーやタグの選択を制限したいこともあるでしょう。
そこで、ユーザーIDごとに管理画面のカテゴリー・タグ一覧やエディターのカテゴリー・タグ選択から特定の項目を除外します。
この記事では、この方法について説明します。
実装手順
以下のコードをfunctions.phpに追加します。
/**
* ユーザーごとの除外設定を取得
*
* @return array ユーザーIDをキーとした除外設定配列
*/
if (!function_exists('get_user_exclude_map')):
function get_user_exclude_map() {
return [
1 => [
'category' => [1],
'post_tag' => [2],
],
2 => [
'category' => [3, 4],
'post_tag' => [5],
],
];
}
endif;
/**
* 親タームの除外対象に子タームを追加
*
* @param array $term_ids 除外対象のタームID配列
* @param string $taxonomy タクソノミー名
* @return array 子タームを含む除外ID配列
*/
if (!function_exists('expand_exclude_ids')):
function expand_exclude_ids($term_ids, $taxonomy) {
$expanded = [];
foreach ($term_ids as $term_id) {
$expanded[] = (int) $term_id;
// 子タームを再帰的に取得
$children = get_term_children($term_id, $taxonomy);
if (is_wp_error($children) || empty($children)) {
continue;
}
$expanded = array_merge($expanded, $children);
}
return array_unique($expanded);
}
endif;
/**
* タームの除外条件を引数に追加
*
* @param array $args WP_Term_Queryに渡す引数
* @param string $taxonomy 対象タクソノミー
* @return array 除外条件を追加した引数配列
*/
if (!function_exists('custom_exclude_terms')):
function custom_exclude_terms($args, $taxonomy = '') {
$user_id = get_current_user_id();
$map = get_user_exclude_map();
if (!isset($map[$user_id][$taxonomy])) {
return $args;
}
$exclude_ids = expand_exclude_ids($map[$user_id][$taxonomy], $taxonomy);
$existing = isset($args['exclude']) ? (array) $args['exclude'] : [];
$args['exclude'] = array_unique(array_merge($existing, $exclude_ids));
return $args;
}
endif;
// Gutenbergのカテゴリー取得
add_filter('rest_category_query', function ($args, $request) {
return custom_exclude_terms($args, 'category');
}, 10, 2);
// Gutenbergのタグ取得
add_filter('rest_post_tag_query', function ($args, $request) {
return custom_exclude_terms($args, 'post_tag');
}, 10, 2);
// 管理画面のカテゴリー・タグ取得
add_filter('get_terms_args', function ($args, $taxonomies) {
if (!is_admin()) {
return $args;
}
foreach ((array) $taxonomies as $taxonomy) {
if (!in_array($taxonomy, ['category', 'post_tag'], true)) {
continue;
}
$args = custom_exclude_terms($args, $taxonomy);
}
return $args;
}, 10, 2);
さいごに
今回紹介した方法を使えば、ログイン中のユーザーごとにカテゴリーやタグの表示・選択を柔軟に制限できます。
これにより、投稿者の入力ミスを防ぎ、サイト運営のルールを徹底しやすくなります。
特に複数ユーザーで運営するサイトでの管理性向上に役立つため、ぜひ活用してみてください。
