プラグインCustom Post Type UIのcptui_current_taxonomyフィルタの使用方法・解説

概要

cptui_current_taxonomyフィルタは、WordPressのCustom Post Type UIプラグインで使用されるフィルタの一つで、カスタムタクソノミーを扱う際にそのデータを変更したり、カスタマイズしたりするのに役立ちます。このフィルタは、特に以下のような機能を実装する際によく使われます。

  1. カスタム投稿タイプに関連するタクソノミーの設定を変更する。
  2. タクソノミーの名前やスラッグを動的に変更する。
  3. タクソノミーの追加または削除を行う。
  4. 特定の条件に基づいてタクソノミーを調整する。
  5. フロントエンドでのタクソノミーの表示をカスタマイズする。
  6. APIを通じてタクソノミー情報を柔軟に扱う。

フィルタの構文は以下の通りです。

add_filter('cptui_current_taxonomy', 'my_custom_taxonomy_function', 10, 2);

パラメータ

  • taxonomies: 現在のタクソノミーの配列。
  • post_type: 関連するカスタム投稿タイプの名前。

戻り値

  • 変更されたタクソノミーの配列。

プラグインのバージョン

  • Custom Post Type UI: 最新版(確認が必要ですが、著名なバージョンは4.x系です)

WordPressのバージョン

  • WordPress 5.0以上での使用が推奨される。

この関数のアクションでの使用可能性

アクション名 使用可能性
mu_plugin_loaded
registered_post_type
plugins_loaded
wp_roles_init
setup_theme
after_setup_theme
set_current_user
init
register_sidebar
wp_loaded
send_headers
parse_query
pre_get_posts
wp
template_redirect
get_header
wp_head

サンプルコード

サンプル1

add_filter('cptui_current_taxonomy', 'add_custom_taxonomy', 10, 2);
function add_custom_taxonomy($taxonomies, $post_type) {
    if ($post_type === 'my_custom_post_type') {
        $taxonomies[] = 'my_custom_taxonomy';
    }
    return $taxonomies;
}

説明: 特定のカスタム投稿タイプに対してカスタムタクソノミーを追加しています。

サンプル2

add_filter('cptui_current_taxonomy', 'change_taxonomy_slug', 10, 2);
function change_taxonomy_slug($taxonomies, $post_type) {
    foreach ($taxonomies as &$taxonomy) {
        if ($taxonomy === 'category') {
            $taxonomy = 'new_category_slug';
        }
    }
    return $taxonomies;
}

説明: すべてのタクソノミーの中で ‘category’ のスラッグを変更しています。

サンプル3

add_filter('cptui_current_taxonomy', 'conditional_taxonomy', 10, 2);
function conditional_taxonomy($taxonomies, $post_type) {
    if (is_single() && $post_type === 'news') {
        $taxonomies[] = 'news_category';
    }
    return $taxonomies;
}

説明: シングル表示のニュース投稿タイプに特定のタクソノミーを追加しています。

サンプル4

add_filter('cptui_current_taxonomy', 'remove_unwanted_taxonomy', 10, 2);
function remove_unwanted_taxonomy($taxonomies, $post_type) {
    if (($key = array_search('unwanted_taxonomy', $taxonomies)) !== false) {
        unset($taxonomies[$key]);
    }
    return $taxonomies;
}

説明: 不要なタクソノミーを削除しています。

サンプル5

add_filter('cptui_current_taxonomy', 'modify_taxonomy_terms', 10, 2);
function modify_taxonomy_terms($taxonomies, $post_type) {
    if ($post_type === 'portfolio') {
        $taxonomies[] = 'portfolio_tag';
    }
    return $taxonomies;
}

説明: “portfolio”投稿タイプに関連するタクソノミーを追加しています。

この関数について質問する


上の計算式の答えを入力してください