How to get Advanced Custom Fields field key from WordPress database?

后端 未结 8 1644
名媛妹妹
名媛妹妹 2020-12-31 01:15

I’m using Advanced Custom Fields with post-type. I have some select custom fields, and I want to show all the label choices from each field.

I’ve tried this way.

8条回答
  •  失恋的感觉
    2020-12-31 02:11

    There's no way to reliably retrieve the key using the name, because the name is metadata, and hence open to change, whereas the key (at least without editing the database manually) isn't.

    However, this function will work with the most recent version of ACF, with a couple of caveats. ACF creates field groups within posts as a custom post type of ACF, but all the data about the fields themselves is held within the post_meta table.

    function get_acf_key($field_name) {
    
        global $wpdb;
    
        return $wpdb->get_var("
            SELECT `meta_key`
            FROM $wpdb->postmeta
            WHERE `meta_key` LIKE 'field_%' AND `meta_value` LIKE '%$field_name%';
        ");
    
    }
    

    A warning: because the field name is stored as part of an array, when finding it via SQL you have to rely on a wildcard search, which is open to errors. As long as all your fields have entirely different names, you're fine, but if for example you have one field called "farm" and another called "farmer", this will error because it will find both fields.

    The only reliable way to update fields is to manually code the key, though this is admittedly clunky, which is what led me here to begin with.

提交回复
热议问题