Home › Forums › General Issues › Get field key by field name › Reply To: Get field key by field name
Hi,
I’ve been struggling with this for some time, and this is my solution, I guess it’s not perfect, but is working for me.
function get_acf_field_keys( $custom_field_slug = '' ) {
$result = array();
$meta_key_start = 'field_';
$acf_args = array(
'post_type' => 'acf'
);
if ( $custom_field_slug !== '' ) {
$acf_args[ 'name' ] = $custom_field_slug;
}
$acf_query = new WP_Query( $acf_args );
if ( $acf_query->have_posts() ) {
while ( $acf_query->have_posts() ) {
$acf_query->the_post();
$meta_values = get_post_meta( get_the_id() );
foreach ( $meta_values as $meta_key => $meta_value ) {
if ( substr( $meta_key, 0, strlen( $meta_key_start ) ) === $meta_key_start ) {
$meta_value_array = unserialize( $meta_value[0] );
$result[ $meta_value_array['name'] ] = $meta_key;
}
}
}
}
wp_reset_postdata();
if ( empty( $result ) ) {
$result = false;
}
return $result;
}
Basically, I’m using WP_Query to iterate through acf posts (Custom fields) & get the metadata, then filter the metadata starting with ‘field_’ to fill an array using the field name as key and the field key as value, to be used like this:
if ( $field_keys = get_acf_field_keys( 'acf_sample-custom-field' ) ) {
if ( isset( $field_keys[ 'sample_field_name' ] ) ) {
$sample_field_key = $field_keys[ 'sample_field_name' ];
}
}
I hope this is helpful for someone.
Welcome to the Advanced Custom Fields community forum.
Browse through ideas, snippets of code, questions and answers between fellow ACF users
Helping others is a great way to earn karma, gain badges and help ACF development!
We use cookies to offer you a better browsing experience, analyze site traffic and personalize content. Read about how we use cookies and how you can control them in our Privacy Policy. If you continue to use this site, you consent to our use of cookies.