Home › Forums › General Issues › Getting the field_key by name
There should be a simple way to do this but in case anyone needs it this is how you get the field_key by name. This example es when the name is pics
$field_key = $wpdb->get_results('SELECT * FROM wp_postmeta WHERE meta_key LIKE \'field_%\' AND meta_value LIKE \'%"name";s:4:"pics"%\' ORDER BY post_id DESC')[0]->meta_key;
The number “4” is there because the word “pics” has 4 characters, so change it based on the length of the name.
Hi @altivan
Since the field_key is saved in the “hidden” meta key you could also just do this:
//add _ before the regular field name.
$field_key = get_post_meta($postid, '_field_name', true);
I’m creating the post at the same time (using wp_insert_post) so ‘_field_name’ doesn’t exist quite yet.
Ah I see.
But shouldn’t that mean that the field key hasn’t been saved to the meta table either at that point? To my knowledge the field key is only saved in one location (for wp_postmeta) and that is as the value of _field_name.
Sorry, I didn’t understood you before; you mean the post_id of the post that acf creates? That makes sense; but I have different versions of the db for each server so the ID is not the same for all, I guess I could make a query to find it out but that would be more work for the same result.
No worries!
What I mean is that whenever ACF saves a value for the first time on a post two fields is created in wp_postmeta. Both field_name and _field_name where field_name contains the actual value and _field_name contains the fields internal key created by ACF.
So if field_name exists in wp_postmeta then _field_name should also exist. The exemption from this is if you create the field_name key/value pair yourself using update_post_meta (for example). Then _field_name wont exist until the post has been “updated” from wp-admin.
The topic ‘Getting the field_key by name’ is closed to new replies.
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.