search ]

Optimizing Database Queries in ACF for Better Performance

Sometimes the functions get_field and the_field of the Advanced Custom Fields plugin are sufficient for pages with a few custom fields. However, for pages with many fields or very complex fields (such as those in Repeater or Flexible Fields), we need to use something a bit more organized.

The original post was written by Julien Melissas. Credits goes to him.

Introduction to Advanced Custom Fields

I really like the Advanced Custom Fields plugin, as you might know if you follow the posts on the Savvy blog. The plugin allows me to develop WordPress sites with custom templates much more easily and enjoyably, especially when dealing with clients with very specific needs.

If you’re interested in learning more about using the ACF plugin, take a look at the guide on Essential Guide to Advanced Custom Fields.

Example Use Case

Let’s say we have a WordPress site—a shelter for animals, for the sake of this example. On this site, we want the ability to easily edit the information for adoptable animals.

If we think about a basic data structure, we will have a custom post type called “pet,” and it should include the following fields:

  • Pet Name – In this case, WordPress provides us with the title of the content type, meaning we use the_title.
  • Pet Type – Let’s say this is a Select Box Field with options for dog, cat, and other.
  • Pet Image (Image Field).
  • Pet Description (ACF wysiwyg).

Using the the_field Function

Now we’ve created a custom post type, and we’re in the single-pet.php file. Let’s print our fields using the the_field function. Remember that the function performs the echo for us:

<?php
//Save Variables
$name = the_title();
$type = get_field('type');
$image = get_field('image');
$description = get_field('description');

if($name) {	?>
    <div class="page-header">
        <h1>
			<?php echo $name; ?>
        </h1>
    </div>
<?php }


if($type) {	?>
    <div class="type">
		<?php echo $type; ?>
    </div>
<?php }


if($image) { ?>
    <img src="<?php echo $image ?>" alt="<?php echo $name; ?>">
<?php }


if($description) { ?>
    <div class="description">
		<?php echo $description; ?>
    </div>
<?php }

?>

Nice and easy—now we have a check for each field before attempting to print it. However, notice that in the top part, we’re making a separate call to the database for each of our fields we’re assigning to a variable.

Most of the time, this is fine, but what if there are 100 fields on that page?? It’s not fun since we’re making a database call for each of the fields we’re assigning to a variable.

Using an Array or the get_fields Function

The Advanced Custom Fields plugin provides us with a function called get_fields. This function was created for those who want to perform a single database call and then iterate over the array where we will receive all the custom fields we created for a specific page.

I definitely prefer this method because it is more efficient (correct me if I’m wrong), and for me, in many cases, it is easier to navigate. You can read more about the get_fields function in the ACF documentation.

So, let’s say we added a dog named “Gins” to our site with some dummy content. Let’s retrieve the field content using get_fields. So, as a start, let’s save the values into a variable:

<?php
// Save Variables
$pet = get_fields();
?>

Now, let’s use var_dump() to print the information of the dog “Gins” on the page:

<?php
// Save Variables
$pet = get_fields();

var_dump($pet);
?>

As you can see, we get back an array. By the way, in this case, we are using an image object to better illustrate the example. Here is the array we received:

Array
(
    [type] => Dog
    [image] => Array
        (
            [ID] => 103
            [id] => 103
            [title] => Just an Image Title
            [filename] => dog.jpg
            [filesize] => 3030
            [url] => https://get-field-example/wp-content/uploads/2018/07/dog.jpg
            [link] => https://get-field-example/test/dog/
            [alt] => Just an Image ALT text
            [author] => 1
            [description] => Just an Image Description
             => Just an Image Caption
            [name] => dog
            [status] => inherit
            [uploaded_to] => 96
            [date] => 2018-07-04 18:17:10
            [modified] => 2018-07-04 18:20:03
            [menu_order] => 0
            [mime_type] => image/jpeg
            [type] => image
            [subtype] => jpeg
            [icon] => https://get-field-example/wp-includes/images/media/default.png
            [width] => 225
            [height] => 224
            [sizes] => Array
                (
                    [thumbnail] => https://get-field-example/wp-content/uploads/2018/07/dog-150x150.jpg
                    [thumbnail-width] => 150
                    [thumbnail-height] => 150
                    [medium] => https://get-field-example/wp-content/uploads/2018/07/dog.jpg
                    [medium-width] => 225
                    [medium-height] => 224
                    [medium_large] => https://get-field-example/wp-content/uploads/2018/07/dog.jpg
                    [medium_large-width] => 225
                    [medium_large-height] => 224
                    [large] => https://get-field-example/wp-content/uploads/2018/07/dog.jpg
                    [large-width] => 225
                    [large-height] => 224
                )

        )

    [description] => 
Objectively matrix interoperable convergence.
)

Isn’t it sexy? The information is neatly organized and ready for use when needed. Let’s assign the desired information to variables and print the values. Note that we are extracting the information directly from the array stored in the $pet variable.

By the way, you can get a lot of information about the image we inserted, such as width, height, description, alternative text, and more. Let’s use this information to display the image in medium size along with the ALT tag for that image. Here’s the code we’ll use:

<?php

//Save Variables
$pet         = get_fields();
$name        = the_title();
$type        = $pet["type"];
$image       = $pet["image"];
$image_url   = $image["sizes"]["medium"];
$image_alt   = $image["alt"];
$description = $pet["description"];


if ( $name ) { ?>
    <div class="page-header">
        <h1>
			<?php echo $name; ?>
        </h1>
    </div>
<?php }


if ( $type ) { ?>
    <div class="type">
		<?php echo $type; ?>
    </div>
<?php }


if ( $image ) { ?>
    <img src="<?php echo $image_url; ?>" alt="<?php echo $image_alt; ?>">
<?php }


if ( $description ) { ?>
    <div class="description">
		<?php echo $description; ?>
    </div>
<?php }
?>

This is just a simple way to improve the number of database calls in Advanced Custom Fields. That’s it.

2 Comments...
  • Lars Faye 23 August 2024, 4:21

    Why did you steal this blog post content and not attribute the original author? Pretty poor morals on your part.

    https://julienmelissas.com/acf-get_fields/

    • רועי יוסף 23 August 2024, 11:23

      You 100% correct. The post was first translated to Hebrew and has the credit to the author. The english version was translated automatically by ChatGPT and many times the translation missing some parts, some times part of the content, code etc.. In this case the credit was removed. I’ve added it manually now.. Thanks for the notice.

Leave a Comment

To add code, use the buttons below. For instance, click the PHP button to insert PHP code within the shortcode. If you notice any typos, please let us know!

Savvy WordPress Development