WPLake > Blog > Smart templates for Meta fields and Posts
  • Deutsch
  • Español
  • Français
  • Italiano

Smart templates for Meta fields and Posts

Time to read: 9 mins

-

ACF Plugins Tutorials

-

Updated 26.01.24

Discover a new way to display your content. Say goodbye to manual post queries and the complexity of types and formats of meta field plugins.

Table of Contents

Throughout our careers, we've encountered only a few websites that haven't used any meta field plugins, and they were quite specific cases.

For clarity, we'll use ACF as an example of the meta field vendor in this article, as Advanced Custom Fields is one of the best plugins for managing meta fields and Custom Post Types (CPTs). For sure, the items we're going to discuss are equally true for any meta-field vendor.

So ACF offers plenty of field types, a user-friendly interface for administrators, and extensive documentation for developers, making it easy to grasp.

On the surface, displaying ACF fields on the front end of a website might seem simple, but in practice, it's often implemented in a less-than-optimal way and takes more time than anticipated.

Challenges in displaying Meta fields directly

#link copied
<p><?php the_field('some_field'); ?></p>

So, in the very simple example above, we are displaying a field. At first glance, it seems straightforward, doesn't it? However, as we delve deeper into development, some issues begin to surface.

Problem #1: Continuously navigating to ACF Groups in wp-admin

#link copied

Firstly, let's talk about field names. Usually, with just the field label, it's nearly impossible to determine the field name. So, every time you need it, you have to visit the list of field groups, find the relevant one, and check the field name.

Now that's sorted. Secondly, what about the return type?

It's straightforward if we're dealing with a text field. But what if it's an image, a select option, or a post? Well, that's where things get a bit more complex. The Advanced Custom Fields plugin offers a wide variety of field types, which is great, but each type has its own unique return formats. This means that even within the same group, you need to check the settings of each specific field.

It's no problem when you're working with ID or Object (WP_Post) returns, but what if it's an array, like in the case of an image option? What keys does it contain? Certainly, if you're working with ACF fields daily, these details are always top of mind. But what if you've been focused on something else for a while?

Problem #2: Consistently needing to refer to the Advanced Custom Fields documentation

#link copied

Now, let's address the second issue: how to access information about the return format and the keys within the returned array, or how to retrieve both a label and its corresponding value. In these scenarios, we find ourselves constantly referring to the ACF documentation for the specific field type. While the documentation is indeed comprehensive, it's still time-consuming.

Problem #3: Synchronizing changes

#link copied

Experience has shown that developers often need to make adjustments to existing fields more frequently than one might anticipate. For instance, a field's return type might change, and changes to the field name and type can occur as well. This necessitates searching through all the theme files to locate the specific code sections responsible for fetching and displaying the field, turning it into a real nightmare.

Furthermore, discrepancies can arise due to coding style variations. While one person may use double quotes in one instance, another might opt for single quotes elsewhere. Additionally, field names can be short and perhaps not entirely unique. Attempting to locate them all under these circumstances is far from enjoyable and incredibly time-consuming.

Problem #4 (Optional): Spaghetti code

#link copied

What haven't we encountered? Especially in cases where changes are made to existing setups rather than starting from scratch. This often leads to a tangled mess of code within templates, leaving everything unclear. Even with a strong desire, it's challenging to discern where a particular piece of code begins and ends.

In the best-case scenario, a developer might opt to write code in the functions.php file, creating a new shortcode to display fields and then placing that shortcode in the intended location. However, when dealing with convoluted themes, there's often neither the time nor the inclination to overhaul the existing structure. Instead, developers tend to create workarounds on the spot, attempting to forget what they've encountered as quickly as possible.

The problem with these functions.php snippets is that they can quickly spiral into files with six or seven thousand lines of code, lacking proper structure, coherence, or clarity. What's the purpose of a particular piece of code? Where is it being utilized? These questions often remain unanswered.

I won't even delve into the issues that arise when attempting to edit, debug, or optimize code structured this way. It's a recurring nightmare for anyone who has had to grapple with it.

Problem #5. Styles and CSS conflicts

#link copied

Developers often create field markups on the fly, and the classes in the markup are generated accordingly, typically based on what first comes to mind. Unfortunately, only a handful are familiar with BEM, and even fewer implement it.

In the worst-case scenario, developers apply styles for the fields globally, resulting in a surplus of unused CSS code. This negatively impacts Google Page Speed and can cause conflicts with other elements due to the generic class names. On the other hand, in the best-case scenario, styles are applied specifically for the target page. However, this can pose challenges when attempting to reuse these styles on other pages.

Summary of the above

#link copied

These issues significantly hamper development speed. Suddenly, what should have taken just a minute for a developer to display four fields now consumes ten! Moreover, the resulting output often harbors numerous issues. The question then arises: who will take on the task of fixing or maintaining it? Sadly, very few are willing to do so.

Challenges in querying Posts directly

#link copied

WP_Query serves as a convenient wrapper for plain MySQL queries, making it relatively easy to construct queries. However, the wide array of arguments, represented as array keys, can be challenging to remember, especially if you don't write queries on a daily basis. Consequently, you often find yourself referring to the WP_Query documentation each time you need to query posts, even when the task primarily involves basic filtering.

Wouldn't it be beneficial to have a user-friendly interface that allows you to define filters? This becomes especially appealing when dealing with Meta and Taxonomy Filters, sparing you the need to search for their names repeatedly. Imagine if such a tool could seamlessly pass the retrieved posts into a template, enabling you to add your own markup around them. Doesn't that sound like a fantastic idea?

Introducing smart templates with the Advanced Views plugin

#link copied

How can we navigate these challenges effectively?

You might suggest using another page builder, but they tend to be bloated and produce cumbersome markup. They often demand mastery of their peculiar UI instead of just a few essential CSS rules, which can be frustrating for developers like me. Furthermore, they don't always offer full control over markup, leading to headaches during customization.

Perhaps you're thinking about exploring other packages or composer libraries, but that typically involves investing time in learning library classes and integrating them into your themes or plugins. However, we're about to discover a better solution.

So, what does the Advanced Views plugin have to offer in addressing these issues?

Advanced Views provides smart templates for effortless content display. It comes with built-in post queries and automated template generation, enabling rapid development while maintaining flexibility.

Let's first clarify what we mean by 'templates' in the context of this plugin: Advanced Views templates are built on the Twig engine. You might be thinking, 'Not bad, but it still requires fetching fields via PHP and writing markup from scratch, not to mention reading Twig documentation'.

Here's where the plugin shines: "Smart templates". This means we don't have to fetch fields or create markup manually from scratch. The plugin provides a solid foundation that covers most use cases. If we require something specific, we can easily customize it. Isn't that nice?

Basics

#link copied

Now, let's take a basic look at how it works.

The plugin introduces two new Custom Post Types (CPTs): ACF View and ACF Card.

  • View for post data and meta fields
    We create a View and assign one or more post fields, the plugin then generates a shortcode that we'll use to display the field values to users. We can style the output with the CSS field included in every View.
  • Card for post selections
    We create a Card and assign posts (or CPT items), choose a View (that will be used to display each item) and the plugin generates a shortcode that we'll use to display the set of posts. The list of posts can be assigned manually or dynamically with filters.

The plugin offers us the convenience of working with familiar WordPress CPTs while taking care of querying and automatically generating Twig markup templates.

All we need to do is specify our requirements, and we'll receive a shortcode ready to be placed anywhere. In the Pro version, instead of the shortcode usage, we can create and use a Gutenberg block (with a simple checkbox toggle). This feature is highly valuable if you are using a block-based theme.

This plugin provides a modular approach right out of the box. We benefit from scoped Views and Cards, thanks to the BEM approach. Additionally, any CSS and JS code we add to a specific View or Card is only printed on pages that use that View or Card. It promotes best practices right from the start.

Now, let's quickly go through the problems to see how they are resolved.

Problem #1: Continuously navigating to ACF Groups in wp-admin

#link copied

We select the post fields from a dropdown, no need to worry about the fields' name or return format.

Problem #2: Consistently needing to refer to the Advanced Custom Fields documentation

#link copied

The plugin supports all field types, and it automatically generates markup based on the field type and return format of the selected fields. Additionally, it follows the BEM format, ensuring readable classes.

Problem #3: Synchronizing changes

#link copied

The Advanced Views plugin stores the field IDs and dynamically retrieves information about the fields from the Advanced Custom Fields plugin. This means we can change the fields as we'd like, including their names and return formats.

Problem #4 (Optional): Spaghetti code

#link copied

No more chaos in functions.php. You'll find a dedicated section in the WordPress dashboard listing all your templates. You can also assign a name and short description to each View or Card, which becomes especially useful when you have a long list to manage. Additionally, a search function is available for convenience.

Usually, the templates themselves are compact, and you have access to a Code Editor, making it easy to amend the code.

Problem #5. Styles and CSS conflicts

#link copied

Now, we get to our favorite feature. The HTML markup is generated using the BEM method, eliminating conflicts. Additionally, each View has its dedicated CSS code field where you can write custom styles for the fields.

This CSS has two advantages:

  1. It doesn't create conflicts (BEM style + View ID), and
  2. It's applied only to the pages where the current View is used, avoiding global styles.

Guides list

#link copied

The Advanced Views plugin supports the default post data, like Featured Image, and meta fields provided by different meta field plugins, including the Advanced Custom Fields plugin. You can find the full list of supported data vendors here and find the list of primary ACF guides below:

It's important to mention that the plugin allows you to display field values from various sources, including the ACF options page. It also integrates seamlessly with any Custom Post Type (CPT), such as WooCommerce Products. Check out the Woo tutorials below.

In addition, the Pro version is available. With the Pro, you unlock these features:

  • Twig template can be customized
  • Filter posts by meta and taxonomies. Use AJAX pagination
  • Repeater field type supported
  • Gallery field supports Masonry style and Lightbox
  • Relationship and Post Object fields have extended support
  • Custom Gutenberg blocks are generated on the fly
  • Plugin’s shortcodes can be added to pages/CPT items without editing code

Note about performance

#link copied

Experienced developers might wonder about potential overhead. After all, it's a wrapper, and one might assume it's much slower than traditional coding. However, this assumption is actually incorrect for several reasons. The plugin's authors have placed special emphasis on optimizing performance.

For instance, they opted to use JSON for storing data in Views instead of traditional metafields. They even conducted a test that demonstrated the negligible difference in performance between the code-based approach and using the plugin with shortcodes. The difference is virtually imperceptible to the naked eye.

User Interface

#link copied

Below, we've included several screenshots of the plugin's user interface, so you can see how it looks. It's simple, intuitive, and familiar.

ACF Views overview page takes you through all the main points.
Overview page takes you through all the main points.
ACF Views allows to get a basic setup in seconds with Demo import.
Get a basic setup in seconds with Demo import.
ACF Views provides list management via the familiar interface.
Views list management via the familiar interface.
ACF Views allow to assign multiple fields within your View.
Assign multiple fields within your View.
ACF Views template generated automatically can be easily customized.
The template generated automatically can be easily customized.
ACF Views allows to display a set of posts with a Card.
Display a set of posts with a Card.
ACF Views posts can be filtered, sorted and styled.
Posts can be filtered, sorted and styled.

Conclusions

#link copied

Advanced Views plugin emerges as a powerful solution for WordPress developers and website owners. It addresses common challenges, simplifies content display with smart templates, and adheres to best practices with BEM-based markup. Furthermore, its emphasis on performance and an intuitive user interface make it a valuable tool for developers seeking to streamline their workflow and enhance content presentation in WordPress.

About the Author
Maxim Akimov

Certified WordPress expert from Ukraine with over 8 years of experience. Advocate of the BEM methodology and the overall modular approach. Loves sporting activities and enjoys going to the gym and regularly plays table tennis.

0 Comments

    Leave a comment

    Reply to 

    Please be considerate when leaving a comment.

    Not shown publicly

    Got it