プラグインAdvanced custom fields(ACF)のacf/input/admin_enqueue_scriptsアクションの使用方法・解説

概要

acf/input/admin_enqueue_scripts アクションは、WordPress管理画面でCustom Fieldsを使用する際に必要なスクリプトやスタイルシートをエンキューするために使用されます。このアクションは、投稿を編集するときに、「enqueue_scripts」アクション中に発生します。具体的には、Advanced Custom Fields (ACF)でカスタムフィールドを編集する際に、特定のJavaScriptやCSSファイルを読み込む必要がある場合に役立ちます。

主に以下の機能を実装する際に使用されます:

  1. カスタムフィールドのエディタを拡張するためのJavaScriptライブラリを追加する。
  2. 特定のページでのスタイルを調整するためのCSSを追加する。
  3. フロントエンドでの挙動を操作するためのスクリプトをエンキューする。
  4. 特定の条件下でのみスクリプトやスタイルを読み込むロジックを実装する。
  5. コンディショナルロジックに基づいたフィールドの表現をカスタマイズする。
  6. ユーザビリティ向上のためのカスタムUIを実装する。

構文

add_action('acf/input/admin_enqueue_scripts', 'my_enqueue_scripts');
function my_enqueue_scripts() {
    // スクリプトやスタイルをここでエンキュー
}

パラメータ

  • なし

戻り値

  • なし

使用可能なバージョン

  • ACFバージョン: 5.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('acf/input/admin_enqueue_scripts', 'enqueue_acf_custom_js');
function enqueue_acf_custom_js() {
    wp_enqueue_script('my-custom-js', get_template_directory_uri() . '/js/custom.js', array('jquery'), null, true);
}

このコードは、特定のカスタムJavaScriptファイルをACFフィールドエディタで読み込むためのものです。

サンプルコード2

add_action('acf/input/admin_enqueue_scripts', 'enqueue_acf_custom_css');
function enqueue_acf_custom_css() {
    wp_enqueue_style('my-custom-css', get_template_directory_uri() . '/css/custom.css');
}

このサンプルは、ACFの管理画面に特定のCSSスタイルシートを追加するためのものです。

サンプルコード3

add_action('acf/input/admin_enqueue_scripts', 'conditional_acf_enqueue');
function conditional_acf_enqueue() {
    if (get_post_type() === 'my_custom_post_type') {
        wp_enqueue_script('my-custom-post-js', get_template_directory_uri() . '/js/post-type.js', array('jquery'), null, true);
    }
}

このコードは、特定の投稿タイプの編集画面でのみスクリプトを読み込む条件を設けています。

サンプルコード4

add_action('acf/input/admin_enqueue_scripts', 'enqueue_admin_scripts_conditionally');
function enqueue_admin_scripts_conditionally() {
    if (is_admin() && isset($_GET['post_type']) && $_GET['post_type'] === 'custom_type') {
        wp_enqueue_script('admin-custom-script', get_template_directory_uri() . '/js/admin-script.js', array(), null, true);
    }
}

このサンプルは、特定の投稿タイプの管理画面にのみスクリプトを追加します。

サンプルコード5

add_action('acf/input/admin_enqueue_scripts', 'add_custom_inline_style');
function add_custom_inline_style() {
    wp_add_inline_style('my-custom-css', '.acf-field { background-color: #f0f0f0; }');
}

このコードは、ACFフィールドのスタイルを変更するためにインラインCSSを追加するものです。

(サンプルコードは独自に作成したもので、引用元はありません。)

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


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