ワードプレスのadd_actionアクションの使用方法・解説

概要

add_actionアクションは、WordPressのプラグインやテーマにカスタム機能を追加するために広く使用されている機能です。このアクションを使用することで、特定のイベントやフックが発生したときに特定の関数を実行できます。add_actionは、ユーザーが指定した関数を特定の位置で呼び出すことで、機能の拡張やカスタマイズを容易にします。以下は、add_actionがよく使用される機能の例です。

  1. テーマやプラグインの初期設定を行う
  2. 管理画面のカスタマイズを行う
  3. 投稿やページの表示をカスタマイズする
  4. ユーザー認証や権限管理の処理を追加する
  5. ウェブサイトのフロントエンドにスクリプトやスタイルシートを追加する
  6. データベースへのデータ挿入や更新を行う
  7. メール送信のカスタマイズを行う
  8. 特定の条件でのリダイレクト処理を追加する

構文

add_action( $hook, $callback, $priority, $accepted_args );

パラメータ

  • $hook (string): フック名。このフックが実行されたときに呼ばれる関数。
  • $callback (callable): フックが実行されたときに呼ばれる関数名。
  • $priority (int): フックの実行順序。デフォルトは10。
  • $accepted_args (int): コールバック関数に渡す引数の数。デフォルトは1。

戻り値

この関数は常に true を返します。

関連する関数

add_actionの関連関数はこちら

ワードプレスバージョン

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');

このコードは、投稿が保存される際に特定のカスタムフィールドに値を追加します。

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


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