プラグインAdvanced custom fields(ACF)のacf/format_valueフィルタの使用方法・解説

概要

acf/format_valueフィルタは、get_fieldなどのテンプレート関数によって読み込まれた後、フィールド $value をフィルタリングします。このフィルタを使用することで、Advanced Custom Fields(ACF)プラグインを使用して追加されたカスタムフィールドの出力をカスタマイズできます。このフィルタは、以下のような機能を実装する際によく使われます。

  1. カスタムデータの形式変更(例:日付の形式を変更)
  2. カスタムフィールドの値に基づいて条件に応じた出力
  3. 特定のフィールドタイプに対する追加情報の付加
  4. フィールドの値を特定の条件でフィルタリング
  5. 出力されるHTMLの変更
  6. 他のプラグインとの統合

構文

add_filter('acf/format_value', 'my_acf_format_value', 10, 3);

パラメータ

  • $value (mixed) – フィールドの値。
  • $post_id (int|string) – フィールドが関連付けられた投稿のID。
  • $field (array) – フィールドの設定配列。

戻り値

  • (mixed) フィルタリング後のフィールドの新しい値。

対応するバージョン

  • Advanced Custom Fields(ACF): 5.0.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: 日付のフォーマットを変更

このサンプルコードは、ACFのDateフィールドの出力形式を変更します。元の形式から「Y年m月d日」の形式に変換します。

add_filter('acf/format_value/type=date_picker', 'my_custom_date_format', 10, 3);
function my_custom_date_format($value, $post_id, $field) {
    return date('Y年m月d日', strtotime($value));
}

引用元: https://www.advancedcustomfields.com/resources/acf-format_value/

サンプル2: カスタムフィールドの条件付き出力

このコードでは、特定のカスタムフィールドが空でない場合にのみ、カスタムメッセージを表示します。

add_filter('acf/format_value/type=text', 'conditional_custom_message', 10, 3);
function conditional_custom_message($value, $post_id, $field) {
    if (!empty($value)) {
        return "カスタムメッセージ: " . esc_html($value);
    }
    return '';
}

引用元: https://www.advancedcustomfields.com/resources/acf-format_value/

サンプル3: HTMLタグの追加

このサンプルでは、カスタムフィールドの値を<strong>タグで囲み、強調表示します。

add_filter('acf/format_value/type=text', 'wrap_value_in_strong', 10, 3);
function wrap_value_in_strong($value, $post_id, $field) {
    return '<strong>' . esc_html($value) . '</strong>';
}

引用元: https://www.advancedcustomfields.com/resources/acf-format_value/

サンプル4: フィールドタイプに基づく出力の変更

このコードでは、特定のフィールドタイプ(例えば、画像フィールド)に対して別の出力を提供します。

add_filter('acf/format_value/type=image', 'custom_image_output', 10, 3);
function custom_image_output($value, $post_id, $field) {
    if ($value) {
        return '<img src="' . esc_url($value['url']) . '" alt="' . esc_attr($value['alt']) . '">';
    }
    return '';
}

引用元: https://www.advancedcustomfields.com/resources/acf-format_value/

サンプル5: 配列からの特定の要素の出力

このサンプルは、カスタムフィールドが配列の場合に特定の要素を出力します。

add_filter('acf/format_value/type=repeater', 'output_repeater_array', 10, 3);
function output_repeater_array($value, $post_id, $field) {
    $output = '';
    if (is_array($value)) {
        foreach ($value as $row) {
            $output .= '<div>' . esc_html($row['sub_field_name']) . '</div>';
        }
    }
    return $output;
}

引用元: https://www.advancedcustomfields.com/resources/acf-format_value/

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


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