概要
Advanced Custom Fields (ACF) の Shortcode フィルタは、コンテンツ エディター内でカスタム フィールドの値を表示するために使用されます。このフィルタは、特に動的なコンテンツを提供する場合に非常に便利です。Shortcode フィルタを使ってカスタムフィールドのデータを簡単に埋め込むことができます。これにより、以下のような多様な機能を実現できます。
- 記事内にカスタムデータを表示する
- 特定の条件に基づいて異なるコンテンツを表示する
- 多言語対応のためのテキスト呼び出し
- リピーターやギャラリーなどのカスタムフィールド表示
- ユーザー情報の表示(例:プロフィールのカスタムフィールド)
- 特定のテンプレートでのデータ取得
構文
add_filter('acf/format_value/type=text', 'my_acf_text_shortcode', 10, 3);
パラメータ
- $value: フィールドの値
- $post_id: 投稿の ID
- $field: フィールドの配列
戻り値
- フィルタを適用した結果のカスタマイズされた値
バージョン
- ACF バージョン:5.0 以上
- WordPress バージョン:4.0 以上
サンプルコード
サンプルコード1: ショートコードを使ってカスタムフィールドの値を表示
このコードは、my_custom_field
というフィールドの値を表示するショートコードを作成します。
add_shortcode('my_custom_field', 'my_custom_field_shortcode');
function my_custom_field_shortcode($atts) {
$post_id = get_the_ID();
return get_field('my_custom_field', $post_id);
}
引用元: https://www.advancedcustomfields.com/resources/shortcode/
サンプルコード2: 特定の条件に基づいて異なるコンテンツを表示
このコードは、カスタムフィールドの値に応じて異なるメッセージを表示します。
add_shortcode('conditional_message', 'conditional_message_shortcode');
function conditional_message_shortcode() {
$value = get_field('my_custom_field');
return $value ? "特別なメッセージ: " . esc_html($value) : "デフォルトのメッセージ";
}
引用元: https://wpbeaches.com/using-acf-and-shortcode/
サンプルコード3: リピーターからのデータを表示
このコードは、リピーターのカスタムフィールドからデータを表示します。
add_shortcode('repeater_data', 'repeater_data_shortcode');
function repeater_data_shortcode() {
$output = '';
if(have_rows('my_repeater_field')) {
while(have_rows('my_repeater_field')) {
the_row();
$output .= '<p>' . get_sub_field('sub_field_name') . '</p>';
}
}
return $output;
}
引用元: https://smashballoon.com/wordpress-custom-fields-and-acf-advanced-custom-fields/
サンプルコード4: 多言語対応のカスタムフィールドを表示
このコードは、WPMLを使用して多言語対応のカスタムフィールドを表示します。
add_shortcode('translated_field', 'translated_field_shortcode');
function translated_field_shortcode($atts) {
$value = apply_filters('wpml_translate_single_string', get_field('my_layer_field'), 'your-domain', 'string-name');
return esc_html($value);
}
引用元: https://wpml.org/en/using-custom-fields-in-wpml/
サンプルコード5: ユーザープロフィールのカスタムフィールドの値を表示
このコードは、現在のユーザーのカスタムフィールドを表示します。
add_shortcode('user_profile', 'user_profile_shortcode');
function user_profile_shortcode() {
$user_id = get_current_user_id();
return get_field('user_bio', 'user_' . $user_id);
}
引用元: https://www.advancedcustomfields.com/resources/getting-started-with-user-profiles/
この関数のアクションでの使用可能性
アクション | 使用可能性 |
---|---|
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 |