Hello,
This is an interesting topic. I’ve already took a deep dive into get_field()
function to take a look at how it works, and also, how to improve it. I also managed to pull out a proof of concept solution to avoid a second DB call in it: https://twitter.com/hwkfr/status/1108079443422179328
As @grahammtbr said, ACF drastically optimized DB calls over the time, and specifically since version 5.7.10 (January 2019) with the introduction of local storage
& rework of cache method. However, there is still one last thing that could (and should) be optimized: the dual post metas my_field
& _my_field
that are saved/loaded by ACF. (Note: Elliot already confirmed he’s working on this).
In fact, get_field()
still does 2 DB calls (if you’re using Json/PHP Sync. 3 without it):
– One to retrieve the reference _my_field => field_123456789
– One to retrieve the value my_field => 2019-11-29
This behavior is mandatory for the moment, because the reference key is used to retrieve field configuration, and specifically the formatted ouput value. In this example, if we’ve set format value to dd/mm/YYYY
, my_field
value will render 29/11/2019
and not 2019-11-29
.
This is why get_post_meta('my_field')
is still faster than get_field('my_field')
. However, if you use get_post_meta('my_field')
, you lose a great part of ACF: formatting ouput values.
There’s a possible hack, which is part of the proof of concept I submitted. If you only use field_key
instead of field_name
in your get_field()
calls, then you can stick to 1 DB call (you also have to add some hooks). However: This means you’ll have to let user customize field_123456789
(because field_123456789
is not really readable), and also, you should make it absolutely unique.
This is why the subject is tricky. ACF let you have multiple fields with the same name
(because the reference is the unique key). This flexibility is a really nice feature of ACF.
Now @alriksson, you mentioned an interesting ‘Get field alternative’ code that I haven’t read before. I must say his trick is really smart. His post is about get_fields()
tho, which retrieve all fields, but still act as get_field()
because references are also retrieved.
I don’t really like the part where you have to set Json path and decode it. But, that made me think about a possible solution to adapt it on get_field()
function. I think it is possible to automatically retrieve the correct json configuration without providing it. This solution avoid the second reference DB call which will make get_field()
essentially work like get_post_meta()
(performance-wise).
I will run some tests, and see what I can make out of it ??
Regards.