Blog posts under the Advanced Custom Fields tag https://webdevstudios.com/tags/advanced-custom-fields/ WordPress Design and Development Agency Mon, 15 Apr 2024 15:59:19 +0000 en-US hourly 1 https://wordpress.org/?v=6.6.2 https://webdevstudios.com/wp-content/uploads/2022/07/cropped-wds-icon.white-on-dark-60x60.png Blog posts under the Advanced Custom Fields tag https://webdevstudios.com/tags/advanced-custom-fields/ 32 32 58379230 Optimizing the WordPress Block Editor Experience https://webdevstudios.com/2022/09/22/optimizing-wordpress-block-editor/ https://webdevstudios.com/2022/09/22/optimizing-wordpress-block-editor/#respond Thu, 22 Sep 2022 16:00:40 +0000 https://webdevstudios.com/?p=25369 Our website agency is currently working on a Headless WordPress Multisite project using Next.js. Development is almost completed for this WebDevStudios client. However, as we’ve begun entering content, we realized that we can make improvements to the editing experience for the client. In this blog post, we outline how by optimizing the WordPress Block Editor Read More Optimizing the WordPress Block Editor Experience

The post Optimizing the WordPress Block Editor Experience appeared first on WebDevStudios.

]]>
Our website agency is currently working on a Headless WordPress Multisite project using Next.js. Development is almost completed for this WebDevStudios client.

However, as we’ve begun entering content, we realized that we can make improvements to the editing experience for the client. In this blog post, we outline how by optimizing the WordPress Block Editor experience, we make it easier for editors to perform their jobs.

Background

The set of websites contains one main site and many subsites. We created several custom post types to handle a variety of content, some of which exist on both the main site and the subsites.

All custom post types contain meta fields, created with Advanced Custom Fields, which are used to add custom content to the post. Additionally, we use the content from two post types from the main site on the subsites.

To build the blocks for this website, we used Advanced Custom Field (ACF) blocks. For a Headless WordPress website, ACF makes it easy to structure data the way we want on the frontend, with minimal extraneous information.

Because of the complexity of information and the challenges of building a headless site, we wanted to make sure the editing experience was as straightforward as possible. We identified five ways to make improvements, optimizing the WordPress Block Editor. It’s all detailed below.

Instructional Text

When creating the blocks, we made sure to clearly label each field and add instructions for editors. We included information like image dimension requirements, character or word length limits, and location specifications (sidebar, main content, etc.).

With these instructions, editors can easily jump in and edit the website. They don’t need to search for documentation or be trained. This detail is especially important with 20+ subsites, each with different editors in different locations.

This is the text editor for a Slide Block, which allows editors to state title, description, upload an image, insert a Link Label, and add a Link URL.

Tabs in Blocks

Advanced Custom Fields provides several layout fields, allowing you to organize content. We leveraged the tab field to separate sections and let users enter specific content in each tab.

For example, if we build a block that contains event details and a sponsor, we can create two tabs. One is for the event information, such as venue, time, etc. The other tab is to input the event’s sponsor information, such as the sponsor’s name, logo, and link.

This sounds so simple and obvious, yet this makes it more convenient than usual for users to add content. Would you prefer a long form where you scroll up and down in the editor or a tabbed block?

This is a screenshot of a Hero Carousel editor with two tabs: Slide Content and Sponsor Details.

Leveraging the power of tabs keeps the user interface and experience better, which allows for optimizing the Block Editor experience for the editor.

Dropdowns

To decrease the chance of human error, we identified places where a dropdown select menu should be used instead of a text field.

Using Advanced Custom Fields, we were able to create custom dropdowns generated from post types and meta fields. For example, we have a block on the subsites that needs to return the ID for an organization, which is a custom post type on the main site.

Initially, we created a Text field for that input, but realized that it opened the door for user error. We changed the Text field to a Select field and queried the organization post type on the main site to get the organization ID from the meta field.

This allowed us to create the options in the Select field with the organization name as the display and ID as the return value. Using a Select field in this way significantly reduces the likelihood of human error, and allows for a more bespoke user experience on the backend.

Readonly Fields

Another way we have addressed the possibility of human error is through ‘readonly’ fields. This is helpful when you want to keep data intact on fields like identifiers imported from an API that doesn’t require any manual editing. The user can view the field values and confirm that content has been entered, but cannot change them.

Frontend Previews

ACF blocks are great for creating complex blocks quickly, but the editor loses the Gutenberg experience of seeing a styled block as they’re building a page. Additionally, since we’re using ACF blocks in a Headless WordPress website, an editor can’t see a preview of the page and blocks they’re editing in the Gutenberg editor.

That’s because the website doesn’t use a standard WordPress theme. Plus, the CSS, Javascript, and PHP aren’t pulled into the preview.

To solve this problem, we included a screenshot of the block as a tab, but our lead developer developed functionality that displays an iframe of the block from the frontend when the “Switch to Preview” button is toggled when editing the site. This lets editors preview the block with the content they’ve entered before saving the page.

Conclusion

Working on this complex site reminded our team that not only is frontend usability important, but the editor user experience is also equally important. If an editor can’t enter content correctly, it doesn’t matter what a website looks like or how it functions.

This brings us to the end of learning the ins and outs of optimizing the WordPress Block Editor experience. We’d love to know the steps you take to improve the editing experience for your WordPress websites. Please tell us in the comments below.

The post Optimizing the WordPress Block Editor Experience appeared first on WebDevStudios.

]]>
https://webdevstudios.com/2022/09/22/optimizing-wordpress-block-editor/feed/ 0 25369
Integrating Advanced Custom Fields + Gutenberg Into wd_s https://webdevstudios.com/2019/10/24/advanced-custom-fields-gutenberg-wd_s/ https://webdevstudios.com/2019/10/24/advanced-custom-fields-gutenberg-wd_s/#respond Thu, 24 Oct 2019 16:00:16 +0000 https://webdevstudios.com/?p=21285 With version 5.8 of Advanced Custom Fields (ACF), a new way to build Gutenberg blocks was introduced. The mission statement of ACF with this pivotal update was to: …radically change the perception of block development in Gutenberg by reducing learning time, hurdles, environment setup and JavaScript knowledge to an absolute minimum. They have done exactly Read More Integrating Advanced Custom Fields + Gutenberg Into wd_s

The post Integrating Advanced Custom Fields + Gutenberg Into wd_s appeared first on WebDevStudios.

]]>
With version 5.8 of Advanced Custom Fields (ACF), a new way to build Gutenberg blocks was introduced. The mission statement of ACF with this pivotal update was to:

…radically change the perception of block development in Gutenberg by reducing learning time, hurdles, environment setup and JavaScript knowledge to an absolute minimum.

They have done exactly that.

For quite some time now, our wd_s starter theme has been powered in part by Advanced Custom Fields. Using the Flexible Content Field, we were able to create a page builder-esque experience for users. This experience lived on the backend when editing posts and pages. We didn’t set out to create a full-on page builder or content builder like the ones we’ve used in the past. We simply understood the need for users to have full control over their content, the placement of that content, and the overall structure of their posts and pages.

And it worked! It worked for a long time. In fact, it still works beautifully.

With the advent of WordPress 5.0, Gutenberg became the hot topic when discussing the CMS. Some absolutely loved the new experience while others reviled it for myriad reasons, such as it felt rushed, it wasn’t fully accessible, and that it was an oftentimes confusing experience.

For us, the issues we experienced working with and building alongside Gutenberg in its development was enough to raise a few red flags. Despite Gutenberg going live in 5.0, we stood back for a moment to evaluate everything before diving head-first into action with the new system. After all, what we had already established wasn’t broken. So, there was no need to “fix” it.

In order to keep our existing workflow in place, we enabled the Classic Editor plugin on new projects to disable Gutenberg and continue working with our tried and true ACF Flexible Content Block system. Once the ACF 5.8 betas and release candidates began rolling out with Gutenberg block support, we began testing the new features with our existing system.

What did we find? Well, to no surprise to anyone on the team, we found that it did exactly what it promised. We were able to spin up new Gutenberg blocks and begin planning a move away from Flexible Content and into a full-on Gutenberg experience.

First Steps

The first thing we needed to figure out when making the transition to ACF-powered Gutenberg Blocks was what we actually needed to include from our existing Flexible Content Blocks. Starting with a blank slate, our content blocks included things like a Call To Action, Hero, and Generic Content block which was a simple WYSIWYG field.

With the robust suite of blocks already available with Gutenberg, we knew we could trim down what we needed to bring over. So, we began to trim the excess and examine if the other blocks we needed served a larger purpose as custom blocks than by “replacing” them with core blocks. We were able to rip the Generic Content block out pretty easily as a standard content block can be added anywhere with Gutenberg.

For our other blocks, though, we found that there were enough little bits and bobbles attached to them that we didn’t want to give up. For instance, our blocks all include the same set of global options including the ability to set a background image, background video, or background color. With the video and image background options, we also include the ability to apply an overlay to make text easier to read when overlaid on the background.

We also have some bonus functionality like Start Date and End Date for those blocks you wish to only display for a specific period of time. Our Hero was also just a bit more fleshed out than what we felt we could accomplish with the core Gutenberg blocks, like setting the aforementioned background options, title, text, and optional link stylized as a button.

Our existing blocks also included Recent and Related Posts. While Gutenberg does offer a Latest Posts widget out of the box, there was just a bit more we were doing with ours that we didn’t want to give up. For instance, the core Latest Posts widget allows for you to specify a post category from which to draw posts but not post tags. You are also limited to selecting a single category or tag, while our block allows for selecting multiple terms in each taxonomy. Along with the previous global block options mentioned and some visual differences, we felt it important to include our own custom block.

Once we got through with our internal review process to determine which blocks we would port over, we were left with:

  • Accordion
  • Carousel
  • Call To Action
  • Fifty-Fifty
  • Hero
  • Recent Posts
  • Related Posts

Creating Your First Block

The first step in creating your Advanced Custom Fields + Gutenberg block is to hook into acf/init and register your block. To ensure that your blocks all have the same global options, though, you’ll first want to establish your baseline supports features for the block:

View the code on Gist.

With this, you’re saying two things: that you only want two layout options for your blocks and that you want to allow for your blocks to have an anchor, or ID, set. In general, the wd_s Flexible Content Blocks had conformed to the width of the content container with the option to go full-width, meaning they will span 100% of the browser width. This is common with blocks with backgrounds, especially heroes. Allowing for an anchor, or ID, was essential as this allows for users to link to other blocks either from the same page or externally.

Next, you’ll need to actually register your block:

View the code on Gist.

This is the important stuff. You’re giving your block a name, description, some keywords, and enqueuing your scripts amongst setting some other baseline ACF settings. Once you have this in place, you simply need to hook in your function like so: add_action( 'acf/init', '_s_acf_init' )

Since you’re calling some other functions and functionality in your block registration, though, you also need to ensure you’re properly tapping into the groundwork Advanced Custom Fields has laid for you.

Adding a Category

In your block registration above, you’ve set your category as wds-blocks. However, that’s a custom category and doesn’t exist by default, which means Gutenberg won’t know how to find these new, fabulous blocks you’re building. Because of that, you need to register your category in a separate function:

View the code on Gist.

Be sure your category slug matches the category name you’re prescribing exactly!

Registering Scripts and Styles

For the Accordion block, you’re calling the _s_acf_enqueue_accordion_scripts callback function to register the scripts necessary to power your block. In general, you may not need to register any scripts—just styles. For the Accordion and Carousel blocks coming form wd_s, though, there is some additional JavaScript needed to make sure the blocks work on the backend.

After all, if you’re looking to deliver a similar experience on the backend as you’re providing on the frontend, you want your JavaScript to work so users can see just how the Accordion collapses and expands before publishing their content. With that in mind, you have to enqueue your scripts:

View the code on Gist.

Within this function, you’re also calling a function to enqueue styles, which looks like this:

View the code on Gist.

You’ll notice the very first thing in both functions is the check for is_admin(). You don’t need to enqueue your scripts anywhere else than on the backend through these methods. The wd_s theme already compiles and enqueues all of the necessary JavaScript and CSS files for the frontend, and here you’re simply concerned with making sure those styles are reflected when adding a block in the editor.

Adding a Field Group

Once your code is in place, the next step is to create the fields for the block. After all, what you’ve done so far is just tell Advanced Custom Fields to create something called “Accordion,” but you’ve yet to actually put something in that block.

Just like with any other Field Group you’d want to create, you’ll navigate to the Custom Fields menu in the Dashboard and click “Add New.” Next, create the fields you need for your block:

ACF Field Group settings page

These will, of course, differ from block to block and for your own personal use cases. All in all, though, this should be familiar to anyone who has worked with ACF in the past. The next step is where things get changed up a bit.

With the previous Flexible Content Block system in wd_s, the “Active” option would be toggled to “Off” for all of the block Field Groups. Then, each block would be cloned in the actual Flexible Content Block Field Group. This helped keep things a bit more sane in the backend. Each block existed as a standalone Field Group, and other reusable Field Groups could be created and cloned into each block like the Background Options and Display Options.

Now, however, you simply need to set your Location rules based on the block you’re creating. Since this is the Accordion block, you want to tell ACF to display these fields when the Block is equal to Accordion. Plus, you now need to ensure you set the Active option to “On” otherwise your block won’t display in the Gutenberg block selector:

ACF Field Group Location settings

And that’s how easy it is to create and register a block in ACF! You can now select your block from the block selector when editing your post… but nothing will happen.

Creating Block Templates

Before anything can actually display, you’ll need to create a template. Ain’t that just the way life works sometimes?

In the block registration way up above in this post, you may have noticed that we’ve set render_callback to _s_acf_block_registration_callback. This is where you’ll let Advanced Custom Fields know exactly where to find the template to display your block.

Keeping with the DRY mentality and not wanting to overload the theme with callbacks for every single block, wd_s includes a handy dandy function which will convert the block name to a slug and inject it into a core WordPress function to grab a template file. This function also checks to make sure the block isn’t expired, which is important because if your block is expired, you don’t want to display it on the frontend at all!

The end result is this tidy little 22-line chunk:

View the code on Gist.

What lives in your actual template file is up to you and will change based on your block, but the important bits to mention are:

  1. Make sure you specify the correct template path
  2. Make sure you name your blocks and template files consistently
  3. In the case of wd_s, add an extra bonus for the Expired Block functionality

Since you have the ability to hide blocks after a specific date, you need a way to communicate this to users on both the frontend and backend. This is easy on the frontend. You simply don’t display the block at all. On the backend, though, you don’t want to hide the block completely because then a user can never edit it or even remove it. That block lives there now forever. It’s comfortable and can’t be evicted. It has attained squatter’s rights.

With a couple of little functions, and some CSS, you’re able to show editors that a block is expired while still allowing them to edit the block in the backend. This is super useful if a user has a block that runs once a week every month and you need to edit the content each month. Now, your users can place your block and let it sit quietly expired with your newest content updates until the new Start Date rolls around.

You’ll begin with this:

View the code on Gist.

And build on that with the following pair of helper functions which check for a block’s expiration and add a class to the block if the block is no longer active:

View the code on Gist.

Now when a block expires, your users will see a helpful notice in the backend:

wd_s Gutenberg expired block message that says, "Your block has expired. Please change or remove the Start and End dates under Other Options to display your block on the frontend.

Our Full Setup

After much back and forth in building, testing, building, testing, and reviewing we are super excited to announce that wd_s is now a Gutenberg-first theme! We merged in our pull request to convert all of our Flexible Content Blocks over to native Gutenberg blocks via ACF about a month ago and are looking forward to seeing how we can grow and expand the awesome functionality ACF provides.

There’s a lot going on here, so feel free to take a peek at our acf-gutenberg.php file to see how everything works together in the wd_s Github repo.

There, you can follow the breadcrumb trail to see some other magic we’re doing with our template files, template tags, and global block options like background elements. While there will always be improvements to be made, those will come in time as we use this new system more and more in real-world situations.

What have you built with the Advanced Custom Fields + Gutenberg integration and where can you see it going from here? Let us know in the comments below!

The post Integrating Advanced Custom Fields + Gutenberg Into wd_s appeared first on WebDevStudios.

]]>
https://webdevstudios.com/2019/10/24/advanced-custom-fields-gutenberg-wd_s/feed/ 0 21285
Creating, Extending, and Upgrading Custom ACF Fields That Use Select2 https://webdevstudios.com/2019/09/17/acf-fields-that-use-select2/ https://webdevstudios.com/2019/09/17/acf-fields-that-use-select2/#comments Tue, 17 Sep 2019 16:00:27 +0000 https://webdevstudios.com/?p=20970 Advanced Custom Fields (ACF) has been around for quite a while now, and it’s super popular. We’re on version 5.x now, and the earliest dated reference documentation I could find was for ACF 2.0 in 2011. There have been some bumps along the way. One of the more recent issues was compatibility of the Select2 Read More Creating, Extending, and Upgrading Custom ACF Fields That Use Select2

The post Creating, Extending, and Upgrading Custom ACF Fields That Use Select2 appeared first on WebDevStudios.

]]>
Advanced Custom Fields (ACF) has been around for quite a while now, and it’s super popular. We’re on version 5.x now, and the earliest dated reference documentation I could find was for ACF 2.0 in 2011. There have been some bumps along the way.

One of the more recent issues was compatibility of the Select2 JavaScript library versions. It was mostly because two other popular plugins, Yoast’s WordPress SEO and WooCommerce, also use Select2. What is Select2? It’s the kick-ass library that lets you transform boring dropdowns to amazing searchable and formattable ones:

A screen grab image of a searchable time zone dropdown menu.

So what’s the big deal with ACF? Well, Select2 has gone through some major revisions as well, most notably the latest Select2 Version 4, which is not backwards compatible with Select2 version 3.x. So, if ACF brings in Version 4 and WooCommerce brings in Version 3, we’ve got problems.

Thankfully, ACF came up with an elegant way to deal with these incompatibilities by checking to see if another plugin had enqueued Version 3 and falling back to using a Select2 Version 3 adapter.

View the code on Gist.

Future-proof it or just fix it?

So, what does this have to do with custom ACF fields? Well, in my case there was an old custom-built ACF field that used Select2. To add the Select2 library to the dropdown, it used a JavaScript call to acf.add_select2() to add it. If you notice in the gist above, acf.newSelect2() was added in ACF 5.6.5, and it replaces acf.add_select2(). In the future, how can we avoid running into this problem? In practice, there are two options:

  1. Extend an existing ACF field that is close to what you want to do.
  2. Create a new (or updating an existing) custom field and use ACF to add Select2.

Your first option is the best one. Here’s why: it simplifies your code investment by leveraging as much as possible from ACF. But, I’m also including the quick-fix instructions specific to the Select2. That way, if you have an existing field that you just need to get working for the time being, you can do that as well.

Option 1: Simplify by extension

One of the fields I needed to fix that used acf.add_select2() was strikingly similar to an existing ACF field—the relational field called Taxonomy. The built-in ACF Taxonomy field also uses Select2. The only difference between the custom field that needed repair and the built-in one is that the custom field would display terms from multiple categories, instead of just one. I had an a-ha moment on a call with Corey Collins when he suggested aloud to let ACF handle the hard work and to just tweak what I needed. Brilliant idea, Corey!

The custom field used to look like this:

View the code on Gist.

Because the AcfFieldMultipleCategories class was essentially a copy of class-acf-field-taxonomy.php, it was almost 600 lines of code.

Instead of extending acf_field, I was able to instead extend acf_field_taxonomy and reduce the PHP code by half and get rid of the custom JavaScript entirely.

View the code on Gist.

What’s different?

Here’s a brief breakdown of the things that are different in the AcfFieldMultipleCategories class and why. You can compare much of the code above to what’s in class-acf-field-taxonomy.php for reference.

  1. The class doesn’t get defined until init. This is because ACF doesn’t load the parent acf_field_taxonomy class right away.
  2. Using initialize instead of __construct: ACF 5.6.0 switched to using initialize instead of __construct so I wanted to follow suit. Our class calls parent::initialize() to get all of the defaults from the taxonomy field, then sets only the fields we want to override.
  3. AJAX actions for wp_acf: These actions are present on the parent, but when they’re registered, they reference a specific instance of an object—the parent acf_field_taxonomy class. We redefine them here to get called on our AcfFieldMultipleCategories instance.
  4. Extra CSS classes in wrapper_attributes: We need our custom field to be rendered with a CSS class of acf-field-taxonomy. This is what the ACF Select2 library is looking for to attach to fields. Select2 will behave exactly how it would on a taxonomy field; we’re just changing the query that happens on the back end.
  5. get_ajax_query has been overridden: It gets called from the parent ajax_query method. We override this to get a result set of terms from multiple taxonomies.
  6. load_value has been overridden and simplified to remove filtering.
  7. render_field has been overridden and simplified to only render a select field because that’s the only option we’re allowing.
  8. render_field_select has been overridden to call a custom get_term_by_id function.
  9. render_field_settings has been overridden to remove the Appearance setting (remember we only want it to display a dropdown). We also removed the Create Terms option, as we won’t be saving any new terms because they’re coming from multiple taxonomies.

Is it a lot? Sure, but it’s far less duplication than before and through simplification, making it less prone to bugs and errors. But if that’s still too much, can you take the easy way out…

Option 2: Just update Select2 calls

This option is an easier short-term solution but may postpone further compatibility issues. Just switch any calls from add_select2 to newSelect2. Any parameters to that function that were previously in snake_case need to be changed to camelCase. Here’s a diff of one that I updated:

-		acf.add_select2( $select, {
+		acf.newSelect2( $select, {
 			ajax: 1,
- 			ajax_action: "acf/fields/post_object/query",
- 			allow_null: 0,
+			ajaxAction: "acf/fields/post_object/query",
+			allowNull: 0,

That’s it. I chose this option for a different and far more complex custom ACF field. It had four inputs in one field, which is nothing like any built-in fields. This one is just going to stay as-is and will try to follow the ACF JavaScript conventions.

Getting Permission

When possible, I prefer the first method of doing things because it’s a better long term solution. You can do Option 2 in less than an hour and then still have time left over to convince your manager that Option 1 is better for the long term. Get some time scheduled to fix it the right way, and it’s a win-win for you and your project.

The post Creating, Extending, and Upgrading Custom ACF Fields That Use Select2 appeared first on WebDevStudios.

]]>
https://webdevstudios.com/2019/09/17/acf-fields-that-use-select2/feed/ 1 20970
Advanced Custom Fields and Gutenberg https://webdevstudios.com/2018/12/11/advanced-custom-fields-and-gutenberg/ https://webdevstudios.com/2018/12/11/advanced-custom-fields-and-gutenberg/#comments Tue, 11 Dec 2018 17:00:36 +0000 https://webdevstudios.com/?p=19363 WordPress 5.0 ships with a new editor called Gutenberg. Here at WebDevStudios, we’re excited to build custom editorial solutions using Gutenberg and to see how the experience evolves from the classic editor. With that said, we’re huge fans of Advanced Custom Fields (ACF). It provides a robust set of field types that enables us to create Read More Advanced Custom Fields and Gutenberg

The post Advanced Custom Fields and Gutenberg appeared first on WebDevStudios.

]]>
WordPress 5.0 ships with a new editor called Gutenberg. Here at WebDevStudios, we’re excited to build custom editorial solutions using Gutenberg and to see how the experience evolves from the classic editor.

With that said, we’re huge fans of Advanced Custom Fields (ACF). It provides a robust set of field types that enables us to create flexible and friendly content management solutions for our clients. The time we save from writing, testing, and maintaining code with ACF makes it worth paying for an ACF PRO license. Our wd_s  starter theme includes commonly-used content blocks built on ACF.

ACF 5.8 has added support for Gutenberg. You can add ACF fields to a Gutenberg block without any JavaScript code. In this article, you will learn how to build a custom Gutenberg block for hero area using ACF without writing a single line of JavaScript code.

Adventurous, right?

ACF and Gutenberg

To build custom blocks using Gutenberg, you must be familiar with writing Modern JavaScript using the latest syntax (ES6, ES7, ES8, JSX), as well as creating components using React. To see this in action, here are some code examples to demonstrate a classic “Hello World” example for Gutenberg.

Custom Gutenberg Block with Vanilla JavaScript:

View the code on Gist.

Custom Gutenberg block with Modern JavaScript:

View the code on Gist.

The second example is smaller and cleaner but requires a build tool setup to compile Modern JavaScript syntax and JSX into browser supported code. You can get a head start by using create-gutenberg-block created by Ahmad Awais to scaffold a Gutenberg block without learning how to set up build tools.

Side Note: Learn JavaScript Deeply

Matt Mullenweg recommended that the WordPress community Learn JavaScript deeply in 2015. If you’re a frontend developer, this still applies—not only for Gutenberg but JavaScript frameworks like React, Angular, and Vue are now widely-adopted and in-demand. Here are some resources to level up your JavaScript skills:

Hero Block

You will be recreating a simpler version of the hero area that is included with wd_s. This is the end result of the custom Gutenberg block that you will create:

Requirements:

  1. Gutenberg (WordPress 5.0)
  2. Advanced Custom Fields PRO 5.8.0

Step 1: Register the Hero Block

ACF introduced acf_register_block function with 5.8, which you will be using to register a custom Gutenberg Hero Block.

The example below shows how to register the hero block. You can drop this function in the functions.php file of your theme.

View the code on Gist.

To learn more details about each parameter of the acf_register_block  function, visit the official documentation.

Step 2: ACF field group for Hero Block

A field group is a set of fields that can be assigned to a WordPress post, page, widget, etc., and now a custom Gutenberg blocks registered with acf_register_block.

Next, you’ll add a new field group for the Hero Block from the Custom Fields page.

The basic field requirements for this block are:

  • Tab field: Block Content
  • Title field
  • Text field
  • Button text field
  • Button URL field
  • Tab field: Background Options
  • Background image field

 

 

Next, assign the field group to the Hero Gutenberg Block.

To reiterate, Block is a new rule type in ACF which refers to all Gutenberg blocks registered with acf_register_block.

Save your changes!

This is how these fields will display in Gutenberg:

Step 3: Set up the Hero Block template

Custom Gutenberg Block created with ACF will use a template file to display it within the Gutenberg editor and on the frontend.

Create a template file template-parts/gutenberg/hero.php within your theme’s folder to match with render_template parameter of acf_register_block defined in Step 1.

The template file will contain HTML markup to add layout and return data from the fields.

View the code on Gist.

The get_field function from ACF is used to get data from the ACF fields.

The rest of the markup is basic HTML for setting up the Hero block’s layout. Just to appreciate the power of this feature by ACF, I want to point out that you didn’t have to write a single line of JavaScript. That’s amazing!

This is how the block looks within the Gutenberg editor:

Step 4: Styling the Hero Block template.

The final step is to style your Gutenberg Block.

To do this, you will be using the enqueue_block_assets action. This hook is used to enqueue assets for Gutenberg’s editor and frontend. If you want to have a separation between frontend and backend styling, you can use enqueue_block_editor_assets to enqueue assets only within the Gutenberg editor.

Drop the following code in your functions.php file to enqueue the stylesheet for your custom Gutenberg Hero Block:

View the code on Gist.

Create gutenberg.css in the root of your theme’s folder and drop the following code for styling the block:

View the code on Gist.

CSS is compiled from Sass.

This finishes your block setup with zero JavaScript code. Congratulations! This is how your Hero Block will look in the Gutenberg editor:

And this is how it will look on the frontend:

 

In my opinion, ACF provides a solid platform that fills the gap between PHP and JavaScript developers. ACF makes the whole Gutenberg Block creation process easier, faster and reliable. Even though I can foresee the limitation of ACF when a complex Gutenberg Block will come in action, I still appreciate and applaud ACF’s approach on making the whole process super simple for all level of developers.

Technically, acf_register_block is extremely powerful considering that a filter can be added to settings array to be used by other themes and plugins to make it even better (or worse).

The post Advanced Custom Fields and Gutenberg appeared first on WebDevStudios.

]]>
https://webdevstudios.com/2018/12/11/advanced-custom-fields-and-gutenberg/feed/ 10 19363