LoginSignup
1
2

More than 5 years have passed since last update.

WordpressのACFにて。field_nameからfield_keyを取得する方法

Posted at

やることはタイトル通り。
公式のフォーラムでも5年ほど更新されるような議題となっているくらいには、需要がある気がしたので、記事にしてみました。

やり方は、下のコードをfunctions.phpに追記するだけ。
もちろんながら、ACF入ってないと、意味がないので注意!

functions.php
/*
 * ACFのフィールドネームからフィールドキー取得
 * 取得できないときには、falseを返す
 * 
 * @param string $field_name
 * @return string|bool
 */
function get_acf_field_key_by_name($field_name){
  //ACFのフィールドをすべて取得
  $args = array(
    'post_type'      => 'acf',
    'post_status'    => 'publish',
    'posts_per_page' => -1,
  );
  $the_query = new WP_Query($args);
  $acf_fields = $the_query->posts;
  wp_reset_postdata();

  //取得したフィールドのIDをもとに、フィールドキーとフィールドネームが保存されているメタ情報を取得する
  global $wpdb;
  foreach($acf_fields as $field){
    $meta_data = $wpdb->get_results(
      $wpdb->prepare("
      SELECT meta_key,meta_value
      FROM $wpdb->postmeta
      WHERE post_id = %d
        AND meta_key LIKE %s
      ", (int)$field->ID, 'field_%')
    );
    foreach($meta_data as $key => $value){
      if(unserialize($value->meta_value)['name'] === $field_name) return $value->meta_key;
    }
  }
  return false;
}
1
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
2