概要
acf/load_field
フィルタは、Advanced Custom Fields (ACF)プラグインで特定のカスタムフィールドが読み込まれる際に、そのフィールド設定を変更するために使用されます。このフィルタは、すでに設計されているフィールドの設定を動的に調整したり、条件によってフィールドの属性を変更するのに便利です。以下のような機能を実装する際によく使われます。
- フィールドのラベルやプレースホルダーの動的変更
- フィールドの選択肢を条件に基づいて変更
- フィールドの表示/非表示を動的に調整
- フィールドのデフォルト値の変更
- 他のフィールドとの連動による設定変更
- 認証されたユーザーの特定の情報を基にフィールドの設定を調整
構文
add_filter('acf/load_field/name=your_field_name', 'your_function_name');
パラメータ
$field
(配列) – 読み込まれたフィールドの設定を持った配列。name
(文字列) – 対象となるフィールドの名前。
戻り値
フィルタリング後の $field
配列を返す必要があります。
バージョン情報
- ACFバージョン: v5.0+
- WordPressバージョン: v4.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_filter('acf/load_field/name=my_field', function($field) {
$field['label'] = '新しいラベル';
return $field;
});
このコードは、特定のフィールドのラベルを動的に変更します。
サンプル2: フィールドの選択肢を条件に基づいて変更
add_filter('acf/load_field/name=my_select', function($field) {
if (some_condition()) {
$field['choices'] = [
'value_1' => '選択肢 1',
'value_2' => '選択肢 2',
];
}
return $field;
});
このコードでは、特定の条件に基づいてセレクトフィールドの選択肢を変更します。
サンプル3: フィールドをログインユーザーに基づいて表示/非表示
add_filter('acf/load_field/name=my_field', function($field) {
if (!is_user_logged_in()) {
$field['wrapper']['class'] .= ' hidden-field';
}
return $field;
});
このコードは、非ログインユーザーに対してフィールドを隠します。
サンプル4: デフォルト値の動的変更
add_filter('acf/load_field/name=my_field', function($field) {
if (current_user_can('administrator')) {
$field['default_value'] = '特別なデフォルト';
}
return $field;
});
このコードでは、管理者ユーザーに特別なデフォルト値を設定します。
サンプル5: 他のフィールドの値に基づくフィールド設定の変更
add_filter('acf/load_field/name=my_field', function($field) {
$related_field_value = get_field('related_field');
if ($related_field_value) {
$field['instructions'] = '関連フィールドの値に基づく設定';
}
return $field;
});
このコードは、関連フィールドの値に基づいてインストラクションを変更します。
引用元: すべてのサンプルコードは著作権フリーで作成しています。具体的なページは存在しませんが、ACFの開発者向けドキュメントを参考にしてください。