Replacing ACF get_field() with WordPress functions significantly reduced db queries.
Bill Erickson wrote that Advanced Custom Fields slows down front end page load time. He also provided an example using WordPress functions instead of those provided by ACF.
Bill’s article claimed that ACF functions may introduce additional database queries. As I am always interested in making my code and sites fast, I begin working on the Belgrove Bouncing Castles code, converting get_field() calls to WordPress functions.
36% reduction in database queries
My first pass used get_post_meta() for the post’s data and calling it again for the image data. It brought the query count down from 58 to 37, with a reduction in memory usage. The page generation time didn’t change much.
The change worked but the image information from post meta was not complete e.g. the full url was not provided. I had to determine the url of the uploads directory and prefix the image path with it.
Then, while browsing the ACF gallery code, I came across the wp_prepare_attachment_for_js() function. The documentation was very encouraging. I tried it out and the function returns an array with a lot of information about the image, with full urls!
I updated my code and it is easier to read. The query count is up a bit, from 37 to 41 but the page load time is down a bit (it is hard to measure accurately as there are a lot of external factors).
But the Featured Image
Next I used Bill’s code to disable ACF on the front end. Unfortunately this introduced a strange error – the ‘featured-image‘ image size was no longer in the list of sizes returned by wp_prepare_attachment_for_js() even though the size is in the list returned by get_intermediate_image_sizes(). As soon as ACF was enabled this image size reappeared. I changed my code to use the ‘medium‘ image size when the ‘featured-image‘ size was not available.
Yet more WordPress image functions
These functions worked, retrieving the featured image, even when ACF was disabled. Furthermore, wp_get_attachment_image() returned completed img markup, making my code even easier to read. The code also appeared to be a little faster!