Blog posts under the blocks tag https://webdevstudios.com/tags/blocks/ WordPress Design and Development Agency Mon, 20 May 2024 17:25:32 +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 blocks tag https://webdevstudios.com/tags/blocks/ 32 32 58379230 Block Patterns Redux: Progression and Application in Modern WordPress https://webdevstudios.com/2024/05/16/wordpress-block-patterns/ https://webdevstudios.com/2024/05/16/wordpress-block-patterns/#respond Thu, 16 May 2024 16:00:57 +0000 https://webdevstudios.com/?p=27166 WordPress Blocks have become a key focus of our work, and WordPress Block Patterns, in particular, have caught my attention. While custom blocks and tools like ACF are important, the introduction of the group block and block patterns has changed how we design. Now, we don’t have to spend as much time creating each custom Read More Block Patterns Redux: Progression and Application in Modern WordPress

The post Block Patterns Redux: Progression and Application in Modern WordPress appeared first on WebDevStudios.

]]>
WordPress Blocks have become a key focus of our work, and WordPress Block Patterns, in particular, have caught my attention. While custom blocks and tools like ACF are important, the introduction of the group block and block patterns has changed how we design. Now, we don’t have to spend as much time creating each custom block or relying only on plugins for complex layouts. With patterns, we can easily make detailed designs right in WordPress.

Let’s take a closer look at how patterns have developed since their introduction in WordPress 5.5, and explore the latest features enabled by the newest APIs.

WordPress Block Patterns

In August 2020, WordPress 5.5 introduced something new called block patterns. These are ready-made pieces that help you design your website pages more easily.

With block patterns, you can choose from many designs to put into your pages. You can make a big headline, a picture gallery, or a testimonial section without doing much work. Block patterns first showed up in the Gutenberg plugin Version 7.7. They were pretty simple at first, but they quickly got better and became useful for building websites.

What’s great about block patterns is that you find them right where you work in WordPress. You don’t need to go anywhere else to use them. It’s like adding a new feature to your website that’s already part of WordPress.

Also, in WordPress 5.5, block patterns worked with reusable blocks. If you had something you used a lot, like your business hours or a contact form, you could still use them with block patterns. But as WordPress improved, block patterns became more powerful, offering more design choices. Using reusable blocks became less important, and block patterns became the main tool for making cool layouts.

Utilizing Block Patterns

Here’s how you can use block patterns:

  1. Making a Pattern: First, design a layout using blocks in the block editor. Then, save it as a pattern and use it in different parts of your website.
  2. Patterns API: WordPress gives developers a way to add and manage patterns to create custom designs.

Block patterns make it easier for everyone to design their website pages. They’re like shortcuts that help you make your website look great without spending much time on it.

Improvements to Block Patterns

One common struggle developers faced was maintaining the structure of patterns while allowing content editing. This meant that users could unintentionally disrupt the layout of patterns when making changes.

Introducing Block Level Locking

WordPress 5.9 introduced a new block level locking mechanism aimed at simplifying block editing within patterns. With this enhancement, users now can selectively apply locks to individual blocks, controlling their movement or removal. This means that developers like myself can now ensure that the structure of patterns remains intact while still allowing users the freedom to edit content within those patterns. It’s a small but significant improvement streamlining the pattern editing process and enhancing the overall user experience.

WordPress 6.0 Enhancements

Version 6.0 introduced significant enhancements for working with patterns and themes, offering developers more flexibility and site owners a smoother experience. Three notable features stand out:

Pattern Registration from Pattern Directory for Themes

In WordPress 6.0, themes can register patterns from the Pattern Directory using the theme.json file. By specifying the desired patterns within the “patterns” field, themes can integrate selected patterns into their design. This simplifies the process of accessing and utilizing patterns directly within themes.

Placement of Patterns in the /patterns Subfolder

Themes now have the capability to define block patterns as files within the /patterns directory. Each pattern file contains metadata headers followed by the pattern’s source code. This organizational structure streamlines the management of patterns within themes, particularly benefiting block themes by reducing reliance on functions.php for control.

Block patterns have progressed significantly since their introduction in WordPress 5.5, with each update to make website design easier. WordPress 5.9 brought enhancements that improved control over block editing within patterns. By WordPress 6.0, patterns were further refined, allowing themes to easily incorporate patterns from the Pattern Directory and define patterns in a separate /patterns subfolder.

These improvements made it simpler for developers to integrate patterns into themes, providing them with more options and solidifying patterns as a key tool for modern website design.

Starter Patterns for Any Post Type

In WordPress 6.1, developers have introduced an enhancement for site builders: the ability to add starter patterns to any post type. Now, you can opt-in to utilize starter patterns when creating content on your WordPress site, whether it’s a blog post, a portfolio item, or any other custom post type.

Reusable Blocks Renamed to Patterns

WordPress 6.3 introduces a terminology change: Reusable Blocks are now called Patterns. This update reflects the broader scope of patterns within the WordPress ecosystem and brings Synced Patterns, a new type of block pattern that behaves similarly to reusable blocks. Synced Patterns enable you to make edits in one place, with changes reflected everywhere the pattern is used. You can also customize individual instances without affecting the original pattern.

For more details, visit Synced Pattern Documentation.

Improved Pattern Management

WordPress 6.4 brings significant improvements to pattern management. Now, you can categorize and filter patterns, making the site-building process simpler. Custom categories help organize patterns effectively, while advanced filtering in the Patterns section of the inserter makes it easier to find and use patterns.

Additionally, introduces the ability to share patterns across sites. You can easily import and export patterns as JSON files directly from the Site Editor’s patterns view, making collaboration easier and workflow smoother. These updates allow users to make better use of blocks and make site building in WordPress even more straightforward. For access to a wide range of patterns, visit WordPress Patterns.

Conclusion

While no specific enhancements were introduced in version 6.5, we entered this stage with a robust set of patterns. With synced controls, locking options, starter patterns, and a wide range of options and controls, patterns have evolved into one of the most powerful tools for site builders. It’s been a long road from the first pattern iteration to what we have now.

Check out the patterns documentation to explore further and unlock the full potential of WordPress Patterns.

The post Block Patterns Redux: Progression and Application in Modern WordPress appeared first on WebDevStudios.

]]>
https://webdevstudios.com/2024/05/16/wordpress-block-patterns/feed/ 0 27166
Block Party: Exploring Interactive WordPress Blocks https://webdevstudios.com/2024/02/06/interactive-wordpress-blocks/ https://webdevstudios.com/2024/02/06/interactive-wordpress-blocks/#respond Tue, 06 Feb 2024 17:00:29 +0000 https://webdevstudios.com/?p=26683 Modern-day WordPress websites use an arrangement of blocks to organize and display content on a page. Some blocks come with the WordPress install, but others are custom-made by third parties. Some of these WordPress blocks are interactive. Interactive WordPress blocks refer to blocks that enable user interaction or engagement directly within the content. These blocks Read More Block Party: Exploring Interactive WordPress Blocks

The post Block Party: Exploring Interactive WordPress Blocks appeared first on WebDevStudios.

]]>
Modern-day WordPress websites use an arrangement of blocks to organize and display content on a page. Some blocks come with the WordPress install, but others are custom-made by third parties. Some of these WordPress blocks are interactive.

Interactive WordPress blocks refer to blocks that enable user interaction or engagement directly within the content. These blocks can include elements like forms, buttons, polls, quizzes, and more, allowing visitors to interact with the content rather than just passively consuming it.

Let’s dive headfirst into a GitHub treasure trove of interactive WordPress blocks. Some may be old, some are new, but nevertheless, there are some interesting finds if you are willing to search.

Quick note, though: in general, it’s recommended to stick with plugins and blocks that can be found in the WordPress Plugin Repository. This plugin marketplace is more than convenient; it has proven to be essential to a great WordPress experience. The repo helps ensure a higher level of quality control.

Below are some fun, interesting, interactive WordPress blocks available on GitHub. These particular blocks exemplify the power of WordPress and where we can expect future WordPress blocks to take us.

Apple Maps Block

The past is the past, and you’re ready to give Apple Maps another chance. Good for you! Apple Maps has been quietly improving and offers a pleasant and modern design and experience. The Apple Maps Block plugin gives you the option to add an Apple Maps interactive WordPress block to your site. This plugin does require you to have or create Apple MapKit credentials. Find it on GitHub.

OpenStreetMap Block

The OpenStreet Map Block allows you to select different tile layer providers like OpenStreetMap, Mapbox, or Stamen, so it has a unique flexibility. You can also adjust map behavior through import/export location data. Unlike Apple Maps, there is no API key required at this moment. There is also a setting for watercolor maps. Now that’s creative! Get the OpenStreetMap Black on GitHub.

Charts Block

The Charts Block adds a selection of colorful chart blocks to your theme. The Data for your chart can be adjusted in a CSV file and then uploaded. I found that these blocks worked better when inserted into a column block to contain the size. Find it on GitHub.

 

Chart Block

This plugin offers a chart block that can switch between different chart types, such as lines, bar, horizontal bar, and pie. Unlike the previously mentioned block, the Chart Block requires that you paste or type in your CSV data in a field.

I’m not sure how this would act with a large data set, but it should be fine for a simple chart. Go to GitHub to access Chart Block.

 

360 Image Block

This plugin allows you to add images with a 360-degree camera to be viewed and panned on your site. 360 Image Block even makes non-360 images feel a little bit 360. There is also a sister plugin that handles 360 videos. Find both 360 Image Block and 360 Video Block at GitHub.

 

 

Honorable Mentions

These interactive WordPress blocks are also worth checking out.

The post Block Party: Exploring Interactive WordPress Blocks appeared first on WebDevStudios.

]]>
https://webdevstudios.com/2024/02/06/interactive-wordpress-blocks/feed/ 0 26683
Quick Tip: Gutenberg Blocks as JSON https://webdevstudios.com/2021/04/20/quick-tip-gutenberg-blocks-as-json/ https://webdevstudios.com/2021/04/20/quick-tip-gutenberg-blocks-as-json/#respond Tue, 20 Apr 2021 16:00:22 +0000 https://webdevstudios.com/?p=23404 Big Ugly Blobs When WordPress saves Gutenberg blocks to the database, it smashes them together as a string of markup. When you query that via the REST-API or WPGraphQL? You get this big ugly blob of HTML: The screenshot above isn’t that bad, but what happens when you have a 2,000 word blog post with Read More Quick Tip: Gutenberg Blocks as JSON

The post Quick Tip: Gutenberg Blocks as JSON appeared first on WebDevStudios.

]]>
Big Ugly Blobs

When WordPress saves Gutenberg blocks to the database, it smashes them together as a string of markup. When you query that via the REST-API or WPGraphQL? You get this big ugly blob of HTML:

This is a screenshot of a string of HTML in GraphQL that looks like a blob of code.

The screenshot above isn’t that bad, but what happens when you have a 2,000 word blog post with images, block quotes and Twitter embeds? When working on a headless frontend, how are you going to create a layout to match your client’s design, when you’re stuck with a big string of HTML?

Maybe reach for regular expressions to pluck out the data? Try using CSS to drill down and style HTML tags? You could totally YOLO that blob of HTML right into a component with dangerouslySetInnerHTML

This is a screenshot of what the previous blob of HTML could look like when using dangerously Set Inner HTML, which is React’s replacement for using inner HTML in the browser DOM.

…but the reality is, losing control over the decision making process for handling data makes for a poor developer experience.

There’s already a standard way to work with APIs that have structured data. To quote the MDN:

JavaScript Object Notation (JSON) is a standard text-based format for representing structured data based on JavaScript object syntax. It is commonly used for transmitting data in web applications (e.g., sending some data from the server to the client, so it can be displayed on a web page, or vice versa).

After reading that definition, you might be asking, “If JSON is a standard way to transmit structured data, why isn’t WordPress doing this with Gutenberg blocks?”

That’s the million dollar question.

WPGraphQL Gutenberg to the Rescue

You’re in luck because the WPGraphQL Gutenberg plugin from Peter Pristas converts Gutenberg blocks to JSON!

Using WPGraphQL, you can query for blocksJSON on a page or post and receive a big ugly blob of JSON instead!

This is a screenshot of a big ugly blob of JSON.

Thanks to both the JSON.parse() and .map() methods, you can convert the JSON response from WPGraphQL into an array of objects, and then .map() over it (kind of like the WordPress Loop). This is standard practice when working with JSON in JavaScript.

The following code snippet parses the JSON response, starts a loop, plucks out the ‘core/paragraph’ block, then passes in the data as props:

This is a screenshot of a code snippet that parses the JSON response.

Thanks to the structure JSON provides, you now have full control over content coming from Gutenberg. Now that’s a good developer experience!

The post Quick Tip: Gutenberg Blocks as JSON appeared first on WebDevStudios.

]]>
https://webdevstudios.com/2021/04/20/quick-tip-gutenberg-blocks-as-json/feed/ 0 23404
WordPress Blocks Backwards Compatibility https://webdevstudios.com/2020/12/29/wordpress-blocks-backwards-compatibility/ https://webdevstudios.com/2020/12/29/wordpress-blocks-backwards-compatibility/#respond Tue, 29 Dec 2020 17:00:01 +0000 https://webdevstudios.com/?p=23127 When I narrowed my development career focus from the PHP world at large to WordPress land, one of the things I enjoyed was WordPress’ commitment to backwards compatibility. As my fellow Minnesota coworker and pragmatist, Richard Aber, would say, new features are often syntactic sugar. In other words, I’m not going to save the world Read More WordPress Blocks Backwards Compatibility

The post WordPress Blocks Backwards Compatibility appeared first on WebDevStudios.

]]>
When I narrowed my development career focus from the PHP world at large to WordPress land, one of the things I enjoyed was WordPress’ commitment to backwards compatibility. As my fellow Minnesota coworker and pragmatist, Richard Aber, would say, new features are often syntactic sugar. In other words, I’m not going to save the world by typing [] instead of array().

But the compatibility landscape of WordPress 5.0 and beyond is much different. The new WordPress block editor Gutenberg is built upon React, and the development pace of React, Gutenberg, and all things JavaScript, in general, is extremely fast. I’m hoping this can serve as a reference or forewarning to those trying to keep up.

Gutenberg Versions

When you’re trying to build a Gutenberg block that is compatible back to WordPress 5.0, navigating this landscape is tricky. Since the Gutenberg editor is developed as a separate project, they have their own versions that get bundled with the major WordPress releases. Trying to find this historical information can be difficult.

After some research and discussion, Senior Backend Engineer, Sal Ferrarello, and Frontend Engineer, Mike England, started a compatibility matrix, which can be found on GitHub. But that didn’t answer all of the questions and solve all of the issues. The official Gutenberg Handbook itself is based on the latest Gutenberg code, which is ahead of the current version of WordPress. Sal opened an issue highlighting that the blocks API documentation is based off of the master branch of Gutenberg.

Block API Reference

Sadly, Sal’s documentation version issue wound up being closed citing:

We’re fixing bugs more than we’re introducing new APIs at this point.

But shortly after the version matrix was created and the version issue filed, a new page showed up in the block editor handbook highlighting the version information:

Versions in WordPress

Still, this “official” table can be a bit confusing. When you look at it, there is a range of Gutenberg versions included in a particular WordPress release:

This is a screenshot of the table. In the left column, it has the header Gutenberg Version. Beneath, in the column, it says eight point six hyphen nine point two. In the right column, the header says WordPress Version. Beneath in the column below, it says five point six.

This is because bug fixes are back-ported into the WordPress release bundle. If you’re using it for an API reference standpoint, always go with the smaller release number.

React Versions

There are several things to think about if you want to provide backwards compatibility to WordPress 5.0. One consideration is the React version included in WordPress.

If you want to create Functional Components instead of Class Components in your Gutenberg block, that requires React version 16.8. WordPress 5.2 is when React 16.8 was included. The easiest way I found to determine which versions of WordPress include which versions of React is to go to the source.

You can find the package.json for WordPress 5.2 here. This includes React 16.8.4. You can replace “5.2” with the version you’d like to investigate.

If you’ve written functional components for distribution in the WordPress.org plugin repository, don’t forget to add the “Requires at least” field to your plugin header:

/**
 * Plugin Name:       My Plugin
 * Requires at least: 5.2
 */

That way, people will not be able to upgrade/install your plugin automatically, unless they’re on WordPress 5.2 or newer.

Block Compatibility

My best advice is to tread lightly and go slowly. React and Gutenberg aren’t great at reporting where your errors are through the browser console. To start, I install the WP-Downgrade plugin so I can easily go back and forth between past and present versions.

If you’ve got something working, test it out and commit your changes. Then, test it for backwards compatibility. When you’re dealing with more than one compatibility error at a time, it’s difficult to hone in on what is going wrong. WordPress might not even load your Guten-block code if there are errors; and it also may not print a message in the console.

The most common issue I’ve encountered is with importing WordPress components. Sometimes things work by importing from a package. Sometimes they’ll only work by destructuring from the global wp object.

WordPress Gutenberg import versus Destructuring Global wp

You may have to experiment with both to see what works for maximum version compatibility.

Example: ServerSideRender

@wordpress/server-side-render

The documentation says once you include it in your package.json you can either import it:

import ServerSideRender from '@wordpress/server-side-render';

Or destructure it from the wp global:

const { serverSideRender: ServerSideRender } = wp;

But neither of those work in WordPress 5.0 (Gutenberg 4.6.1) because @wordpress/server-side-render wasn’t a package yet. It also isn’t at wp.serverSideRender at that time, it’s at wp.components.ServerSideRender.

If you want it to work in WordPress 5.0, you’ll need to destructure it from the wp global like this:

const { ServerSideRender } = wp.components;

In new versions of WordPress, you’ll get this warning message in the console:

wp.components.ServerSideRender is deprecated. Please use wp.serverSideRender instead.

The user may never see that, and it sure beats them seeing this in the editor:

This is a screenshot of a warning that could be seen in the WordPress Editor, that says, "Your site doesn't include support for the WP hyphen Strava back slash activity block. You can leave this block intact or remove it entirely."

Deprecation Hunting

Other popular components that have moved since WordPress 5.0 are BlockControls and InspectorControls. I’ve got them working in 5.0 with the following browser warnings:

wp.editor.BlockControls is deprecated. Please use wp.blockEditor.BlockControls instead.
wp.editor.InspectorControls is deprecated. Please use wp.blockEditor.InspectorControls instead.

But how did I find them? Going to the source is always best. Clone the Gutenberg project and check out the tag for the most recent version of WordPress:

git clone git@github.com:WordPress/gutenberg.git
cd gutenberg
git checkout v8.6.0

You can browse the tags on GitHub or list them with git tag. After checking out the tagged version, start looking for the component that’s not working. For InspectorControls I used grep to find it:

$ grep -r InspectorControls .
...
packages/editor/src/components/deprecated.js: 'InspectorControls'
...

There’s a lot of output when searching, but the path of the deprecated.js file gave me a clue: packages/editor. It used to be in wp.editor and is now in wp.blockEditor (which has the path packages/block-editor). Again, the documentation isn’t great, so you have to do some sleuthing and gather context clues.

Good luck out there, and always keep compatibility in mind!

The post WordPress Blocks Backwards Compatibility appeared first on WebDevStudios.

]]>
https://webdevstudios.com/2020/12/29/wordpress-blocks-backwards-compatibility/feed/ 0 23127
How to Enable Frontend Editing with Gutenberg Blocks (Part 2) https://webdevstudios.com/2020/08/11/frontend-editing-gutenberg-blocks-2/ https://webdevstudios.com/2020/08/11/frontend-editing-gutenberg-blocks-2/#comments Tue, 11 Aug 2020 16:00:34 +0000 https://webdevstudios.com/?p=22561 Welcome back! In Part 1, we covered preparing our block for frontend editing by implementing unique block identifiers, rendering the block dynamically, and establishing a frontend component. Now, we’ll dive into the WordPress REST API to set up a custom route and call that route asynchronously from our frontend component. Note: The example snippets in Read More How to Enable Frontend Editing with Gutenberg Blocks (Part 2)

The post How to Enable Frontend Editing with Gutenberg Blocks (Part 2) appeared first on WebDevStudios.

]]>
Welcome back! In Part 1, we covered preparing our block for frontend editing by implementing unique block identifiers, rendering the block dynamically, and establishing a frontend component. Now, we’ll dive into the WordPress REST API to set up a custom route and call that route asynchronously from our frontend component.

Note: The example snippets in this post are modified from @ravewebdev/initiative-tracker, my Character Initiative Tracker block plugin for table-top role-playing games, which was built with @WebDevStudios/create-block, the WDS block scaffolding CLI tool.

3. WP REST API Implementation

Before we continue building out our frontend component, let’s take a PHP break and set up a route with the WP REST API, so we can plug that into our editing functionality:

  • Set up custom route
  • Localize route

3.1. Set Up Custom Route

If you’ve been tinkering in WordPress for a while, you may have handled frontend interactivity via the AJAX API (admin-ajax.php) with jQuery. These days, though, many engineers prefer to take advantage of the newer WordPress REST API instead, given its potential to simplify the development process and possibly improve performance. We’ll be using the WP REST API here, but feel free to go old school with the AJAX API if you want; keep in mind, however, you may need to alter a substantial amount of the code included throughout this post to make it work.

View the code on Gist.

To start, we’ll register our custom route with register_rest_route(), which accepts three parameters:

  • namespace: This is a unique string representing the current plugin/package namespace, ideally specifying a version number.
  • route: This is the custom route URL, optionally with Regex patterns to match required arguments passed to our route. We’ll use the pattern (?P<id>[d]+) to ensure a integer is passed to our route, representing our post ID.
  • args: This signifies the route options, which can be an array of options for a single endpoint or a multi-dimensional array for multiple endpoints. We’ll use the former since we’re only implementing one endpoint for our route. These are the options we need to worry about right now:
    • methods: This defines the method or methods accepted for this endpoint. We’re using WP_REST_Server::EDITABLE here, which is an alias for the POST, PUT, and PATCH HTTP methods.
    • callback: This is the function that’s called when our endpoint is successfully requested.
    • permission_callback: This function allows us to perform a permissions check when our endpoint is requested, prior to the callback being run.

Since our endpoint is accepting editing methods, we don’t want absolutely anyone to access it, right? Well, that’s where our permissions callback comes into play. As we defined our route with a required ID argument to represent the current post ID, we’ll retrieve that first, then implement several checks to ensure only permitted users are allowed to proceed.

  • Check if user is currently logged in via is_user_logged_in(), as we don’t want to allow any non-logged-in users to access our endpoint.
  • Check if the post ID we were passed represents a valid post object with get_post().
  • Check if the current user has the desired capability with current_user_can(). As we’ll be editing an already-published post with our block, we’re checking for the capability edit_published_posts, which, by default, is available to Super Admin, Administrator, Editor, and Author roles, but feel free to pick another or create your own capability for this step.
  • Finally, if the current user did not pass our previous capability check, see if they are the author of the current post.

Now, we’re on to our main callback function! We’d normally need to check for and validate our nonce, but the WP REST API handles this all automatically.

Let’s continue and retrieve the parameters from our request, similar to how we did in the permissions callback. As before, we’ll need the target post ID (id), but we’ll also need to get our target block ID (block_id) to ensure we’re modifying the correct block in our post. Likewise, here is where we’ll retrieve any other block attributes we want to work with or update.

Next, we’ll use get_post_field() to fetch the post’s content and feed it into parse_blocks(), which, as the function name suggests, parses the post’s content, converting block comments into associative arrays of block data.

Now we can iterate over the resulting array of block data, using array_map(), passing any necessary data or attributes we’ll need via use. Here, we’re merely passing our block ID, but you’ll likely want to pass some block attributes as well. We’ll perform a quick two-part check, allowing us to return early if this isn’t the block we’re looking for:

  1. Compare the current block’s name, via the blockName value, to our custom block’s name, which we set all the way back in Part 1, step 1.1.
  2. Compare the current block’s ID, via the id value within the block’s attrs array, to our target block’s ID.

Once we pass the above check, we can start modifying our block’s attributes or other values (e.g., innerContent), like in the commented-out example above, and return the updated block array.

After we’ve modified our block, we need to save the post’s content with wp_update_post(), which, for our purposes, will take an associative array of the post’s ID and content. Be careful here! Since we parsed the content earlier into an array of blocks, we’ll need to transform it back into block comments via serialize_blocks().

Finally, we’ll end our function by returning an appropriate message that we can later display to the user. I like to return an instance of WP_REST_Response, which allows us to specify an HTTP status code along with our message.

3.2. Localize Route

While it’s totally possible to skip this section and hard-code our route path in our frontend JavaScript code, let’s try localizing our route so we can access that value dynamically later on. This is particularly handy if there’s any possibility you might change anything about your route path (e.g., version number) later on.

View the code on Gist.

Here we’ll localize our custom route with wp_localize_script(), which takes three parameters:

  • handle: The script handle to attach our data to—here it’s the handle for our frontend script file
  • object_name: The JavaScript object name, which we’ll use later to retrieve our route path
  • data: This is an array of data to assign as properties of our object variable. We’ll pass the simple relative path of our route (without the post ID route argument).

Note: Depending on how you implement your REST request on the frontend, you may also want to set up and localize a nonce here manually, using wp_rest as the nonce action, given that the WP REST API has some built-in handling for this nonce action; however, since we’re using the WP JavaScript API here, that’s handled automagically.

4. Frontend Updates

Now, we’ll dive back into our frontend component and pull everything together:

  • Handle component state (optional)
  • Perform request

4.1. Handle Component State

To prepare for sending the edit request to our route, we’ll set up some more state variables to help keep track of everything. This section is technically optional, as it’s not actually required to implement our frontend editing process, but these extra state variables help provide feedback to the end user.

View the code on Gist.

While adding loading state isn’t strictly necessary, it is useful for letting the user know that something is happening behind the scenes. There are many possibilities, such as disabling a submit button (via setting its disabled property to the value of our loading variable—e.g., disabled={ isLoading })—displaying a loading GIF, or otherwise communicating to the user that processing is occurring.

Next, we’ll set up another state variable to assist with displaying success and error messages to the user. We’ll utilize useEffect() again, this time passing an array with a single value, notice, which will instruct our effect to run each time the value of notice changes. Our purpose here is to automatically clear the notice after a set period of time—one minute (60,000 ms) in our case—using setTimeout(), then return a call to clearTimeout() to remove the timer.

That said, feel free to adjust the timing or remove this block of code altogether, if you want to display the notice indefinitely or remove it another way (e.g., with a close button).

One thing to keep in mind here: state variables don’t always work as expected within setTimeout() callbacks. The value of a state variable within the callback will be its value when the timeout was scheduled and not when the callback actually runs. Luckily, we can ignore this quirk here, as we don’t care what the value was, only what we want to set it to (null); however, if we did want to check the current value of our state variable from within our callback, we could make use of another React hook, useRef().

4.2. Perform Request and Update Block

At last, we’re ready to implement a fetch request to our custom WP REST API route, save our block data, and show some update notices.

View the code on Gist.

To start, we’ll create a new asynchronous function to hold our update process and begin by changing our state: setting our loading variable to true and our notice variable to null.

Then we’ll make an asynchronous call to our custom route via apiFetch(), which is a wrapper around window.fetch(), accepts an object of options as a parameter, and returns a Promise object. We’ll pass the following options:

  • path: This is the relative path to our REST route, which is automatically prepended with the current site’s WP REST API’s root URL.
  • method: This is the HTTP method we’ll be using to access our route. Here we’ll simply employ POST.
  • data: This is an object of data to be passed to our route. We’ll use the spread operator to pass all our component attributes through to our route.

Since we already set up our route callback back in step 3.1., we can now proceed to handle the response from our callback.

For a successful response, we’ll create a then() block, in which we can update any component props. While not required, this allows us to “reset” the data attributes in our frontend component’s props to the values newly saved in the database. Then we’ll return a formatted object with the response type and message.

In the event of an error, our catch() block will similarly return a formatted response type and message, with a slightly different format. In our callback, we return an instance of WP_REST_Response on success, but an instance of WP_Error is generally passed on failure; the former returns a string for a message, whereas the latter returns an object, with the actual error message saved as the message property.

Next, we’ll toggle our isLoading state back to false and update our notice state to the value of the response object we just created.

Finally, we’ll output any success/error notice to the end user in the return statement of our component. We’ll use the type property to determine the class and role attributes for our DOM element (the latter of which is valuable for accessibility), then output the actual message as text.

Here’s how it looks in action:

View the code on Gist.

Conclusion

Congrats! If you followed all that, you’re well on your way to implementing frontend editing with blocks!

There’s plenty to keep in mind when transforming blocks in this way, from block identifiers, to double rendering with PHP and JavaScript, to creating custom routes via the REST API, to performing fetch requests and displaying status messages. In the end, it boils down to leveraging as much of the built-in codebase as possible and letting it do the heavy lifting, with a healthy dose of experimentation, of course.

If you use this tutorial to build or extend your own block with frontend editing, let us know how it goes by commenting below. And if you’ve implemented frontend block editing by another method, please share your tips and techniques with us in the comments.

The post How to Enable Frontend Editing with Gutenberg Blocks (Part 2) appeared first on WebDevStudios.

]]>
https://webdevstudios.com/2020/08/11/frontend-editing-gutenberg-blocks-2/feed/ 4 22561