概要
woocommerce_after_register_taxonomy
は、WooCommerceで新しいタクソノミーが登録された後に実行されるフックです。このアクションは、タクソノミーを使用して商品の分類をよりカスタマイズする際に役立ちます。具体的には、プラグインやテーマが新しいタクソノミーを追加する場合に、その追加後に特定の処理を行いたいときに使用されます。
よく使われる機能の例
- 新しいタクソノミーの設定を行う
- タクソノミーのカスタムメタデータを追加する
- タクソノミーに関連するオプションや設定を作成する
- タクソノミーと他のカスタムポストタイプの関係を定義する
- 特定の条件に基づいてタクソノミーの表示方法を変更する
- 商品フィルター機能を拡張する
構文
do_action('woocommerce_after_register_taxonomy', $taxonomy);
パラメータ
$taxonomy
: 追加されたタクソノミーの名前(文字列)。
戻り値
このアクションは戻り値を返しません。
使用可能なバージョン
- WooCommerce: 3.0以降
- WordPress: 4.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_action('woocommerce_after_register_taxonomy', 'add_custom_meta_to_taxonomy', 10, 1);
function add_custom_meta_to_taxonomy($taxonomy) {
if ($taxonomy === 'product_cat') {
register_meta('term', 'custom_meta_key', [
'type' => 'string',
'description' => 'A custom meta field for product categories',
'single' => true,
'show_in_rest' => true,
]);
}
}
このコードは商品カテゴリーにカスタムメタデータを追加するもので、タクソノミーが登録される際に実行されます。
サンプルコード 2: タクソノミーの表示設定を変更
add_action('woocommerce_after_register_taxonomy', 'modify_taxonomy_display', 10, 1);
function modify_taxonomy_display($taxonomy) {
if ($taxonomy === 'product_tag') {
add_filter('woocommerce_product_tag_args', function($args) {
$args['orderby'] = 'name';
return $args;
});
}
}
このコードは、商品タグの表示順序を変更するもので、新しい商品タグタクソノミーが登録された後に実行されます。
サンプルコード 3: タクソノミーとカスタムフィルターの関連付け
add_action('woocommerce_after_register_taxonomy', 'link_taxonomy_with_filter', 10, 1);
function link_taxonomy_with_filter($taxonomy) {
if ($taxonomy === 'product_cat') {
add_action('woocommerce_product_query', function($query) {
if (isset($_GET['custom_filter'])) {
$query->set('tax_query', [
[
'taxonomy' => 'product_cat',
'field' => 'slug',
'terms' => sanitize_text_field($_GET['custom_filter']),
]
]);
}
});
}
}
このコードは、新しい商品カテゴリーに基づいて商品フィルターを追加するもので、タクソノミーが登録後に実行されます。
サンプルコード 4: 他のポストタイプとの関係を定義
add_action('woocommerce_after_register_taxonomy', 'define_relationship_between_post_types', 10, 1);
function define_relationship_between_post_types($taxonomy) {
if ($taxonomy === 'custom_taxonomy') {
register_post_type('custom_post_type', [
'labels' => [
'name' => 'Custom Posts',
'singular_name' => 'Custom Post',
],
'public' => true,
'has_archive' => true,
'supports' => ['title', 'editor'],
]);
}
}
このコードは、新しいタクソノミーに関連付けられたカスタムポストタイプを登録するもので、タクソノミーが登録された後に実行されます。
サンプルコード 5: タクソノミーの用語を自動で作成
add_action('woocommerce_after_register_taxonomy', 'automatically_create_terms', 10, 1);
function automatically_create_terms($taxonomy) {
if ($taxonomy === 'product_cat') {
wp_insert_term('New Category', 'product_cat');
}
}
このコードは、新しい商品カテゴリーが登録されたときに「New Category」という用語を自動的に作成します。タクソノミーが登録された際に実行されます。