概要
woocommerce_register_post_type
アクションは、WooCommerceプラグインの一部であり、主にWooCommerceが使用するカスタム投稿タイプを登録する際に利用されます。このフックを使用することで、開発者は製品や関連エンティティのカスタム投稿タイプを拡張し、特定の機能を追加できます。よく使われるシナリオには以下が含まれます。
- 新しい製品タイプの登録
- 製品属性のカスタマイズ
- メタデータの追加
- 製品のカスタム分類の追加
- 特定のフィールドの非表示/表示切り替え
- WooCommerceのデフォルトのスラグやUIを変更
構文
add_action( 'woocommerce_register_post_type', 'your_custom_function' );
function your_custom_function() {
// カスタム処理
}
パラメータ
- なし
戻り値
- なし (このアクションは値を返さないため)
使用可能なバージョン
- 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_register_post_type', 'add_custom_product_type' );
function add_custom_product_type() {
register_post_type( 'custom_product', array(
'labels' => array(
'name' => 'Custom Products',
'singular_name' => 'Custom Product'
),
'public' => true,
'has_archive' => true,
'supports' => array( 'title', 'editor', 'thumbnail' )
) );
}
このコードは、WooCommerceに新しい製品タイプ「Custom Product」を追加しています。製品名やアイキャッチ画像を設定できるようになります。
引用元: https://developer.wordpress.org/reference/functions/register_post_type/
サンプルコード2: 製品メタデータの追加
add_action( 'woocommerce_register_post_type', 'add_custom_product_meta' );
function add_custom_product_meta() {
add_post_meta( get_the_ID(), '_custom_meta_key', 'Custom Value', true );
}
このコードは、特定の製品にカスタムメタデータを追加するために使用されます。
引用元: https://developer.wordpress.org/reference/functions/add_post_meta/
サンプルコード3: 製品のカスタム分類の追加
add_action( 'woocommerce_register_post_type', 'register_custom_taxonomy' );
function register_custom_taxonomy() {
register_taxonomy( 'custom_taxonomy', 'custom_product', array(
'label' => 'Custom Taxonomy',
'rewrite' => array( 'slug' => 'custom_tax' ),
'hierarchical' => true,
) );
}
このコードは、「Custom Product」に関連するカスタム分類である「Custom Taxonomy」を登録します。
引用元: https://developer.wordpress.org/reference/functions/register_taxonomy/
サンプルコード4: 製品属性の非表示化
add_action( 'woocommerce_register_post_type', 'hide_custom_product_attributes' );
function hide_custom_product_attributes() {
remove_post_type_support( 'custom_product', 'custom_attributes' );
}
このコードは、カスタム製品タイプに対してデフォルトの製品属性を非表示にします。
引用元: https://developer.wordpress.org/reference/functions/remove_post_type_support/
サンプルコード5: WooCommerce製品スラグの変更
add_action( 'woocommerce_register_post_type', 'change_product_slug' );
function change_product_slug() {
global $wp_post_types;
if ( isset( $wp_post_types['product'] ) ) {
$wp_post_types['product']->rewrite['slug'] = 'shop-item';
}
}
このコードは、WooCommerceの製品スラグを「shop-item」に変更します。
引用元: https://developer.wordpress.org/reference/classes/wp_post_type/