概要
add_action
アクションは、WordPressのプラグインやテーマにカスタム機能を追加するために広く使用されている機能です。このアクションを使用することで、特定のイベントやフックが発生したときに特定の関数を実行できます。add_action
は、ユーザーが指定した関数を特定の位置で呼び出すことで、機能の拡張やカスタマイズを容易にします。以下は、add_action
がよく使用される機能の例です。
- テーマやプラグインの初期設定を行う
- 管理画面のカスタマイズを行う
- 投稿やページの表示をカスタマイズする
- ユーザー認証や権限管理の処理を追加する
- ウェブサイトのフロントエンドにスクリプトやスタイルシートを追加する
- データベースへのデータ挿入や更新を行う
- メール送信のカスタマイズを行う
- 特定の条件でのリダイレクト処理を追加する
構文
add_action( $hook, $callback, $priority, $accepted_args );
パラメータ
$hook
(string): フック名。このフックが実行されたときに呼ばれる関数。$callback
(callable): フックが実行されたときに呼ばれる関数名。$priority
(int): フックの実行順序。デフォルトは10。$accepted_args
(int): コールバック関数に渡す引数の数。デフォルトは1。
戻り値
この関数は常に true
を返します。
関連する関数
ワードプレスバージョン
add_action
は、WordPressの初期バージョンから使用可能です。
コアファイルのパス
wp-includes/plugin.php
この関数のアクションでの使用可能性
アクション | 使用可能性 |
---|---|
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 | 〇 |
以下は、add_action
アクションのサンプルコードです。
サンプルコード1: カスタム投稿タイプの作成
function create_custom_post_type() {
register_post_type('custom_post', [
'label' => 'カスタム投稿',
'public' => true,
'supports' => ['title', 'editor', 'thumbnail']
]);
}
add_action('init', 'create_custom_post_type');
このコードは、WordPressのinit
アクションにフックして、カスタム投稿タイプ「カスタム投稿」を作成します。
サンプルコード2: CSSファイルの追加
function add_custom_styles() {
wp_enqueue_style('custom-style', get_template_directory_uri() . '/css/custom.css');
}
add_action('wp_enqueue_scripts', 'add_custom_styles');
このコードは、wp_enqueue_scripts
アクションを使用して、テーマのカスタムCSSファイルをウェブサイトに追加します。
サンプルコード3: メール送信のカスタマイズ
function send_custom_email($user_id) {
$user_info = get_userdata($user_id);
wp_mail($user_info->user_email, 'Welcome!', 'Thank you for joining us!');
}
add_action('user_register', 'send_custom_email');
このコードは、ユーザーが登録された際(user_register
アクション)に、カスタマイズされたメールを送信します。
サンプルコード4: ウェブサイトのタイトルの変更
function modify_site_title($title) {
return '新しいサイトタイトル';
}
add_action('wp_title', 'modify_site_title');
このコードは、wp_title
アクションにフックし、ウェブサイトのタイトルをカスタマイズします。
サンプルコード5: 投稿の保存時に自動的にフィールドを追加
function save_custom_post_meta($post_id) {
if (get_post_type($post_id) == 'custom_post') {
update_post_meta($post_id, 'custom_field', '値');
}
}
add_action('save_post', 'save_custom_post_meta');
このコードは、投稿が保存される際に特定のカスタムフィールドに値を追加します。