Gutenberg Development with Examples: Google Maps (part 3)

Published in WordPress.

Welcome to the third and last post on how to create a maps plugin for Gutenberg. Our last post was quite dense and we saw a lot of different things: the attributes our block has, how to insert a map using a React component, how to use WordPress components or even create our own components to define the user interface, etc. Today we’ll be discussing something simpler.

In this post we’ll see how to render the Google Maps map in the front-end. To do this, we will take a closer look at save.js and we will make a few changes to the plugin so that everything works as expected. I will also use this last post to comment on any point that may have been unclear until now.

How to Save Our Map Block to Display It in the Front-End

To display the map in the front-end we first have to define the HTML we want to be rendered in the front-end. In a Gutenberg block, this is achieved by defining the save method of the registerBlockType function. As I already mentioned in the previous post, this method is defined in the file save.js in packages/blocks/nelio-maps/.

Again, this is an extremely simple function to understand:

  • From line 7 to 25 we extract all the attributes that are relevant to our block. That is, all the attributes that we defined in attributes.js and that tweak the appearance of our map.
  • In line 41 we open the div that will serve as a container for the block.
  • In line 47 we find a div that will wrap the map itself. Look at something very interesting: this div includes all the attributes object in its definition. This means that all the properties in attributes (for example, 'data-lat': lat of line 34) will be rendered as HTML attributes (for instance, assuming that the variable lat is 2.48171, lat will appear in the final HTML as data-lat="2.48171").
  • On line 49, a small div is added containing the coordinates of the marker.
  • On line 59, the contents of the RichText that we had defined in edit.js.

So, in essence, the method save generates an HTML that contains all the attributes that are relevant to render a map in the front-end. So, what could go wrong? Well, if you were to open the front-end now, all you’d see would be this:

Screenshot where a map should look and not seen
Screen capture where a map should be seen. Oh wait… What’s going on?

An empty block that only has some RichText content. What happened?

How to Modify the Plugin to Render a Google Map Created with our Gutenberg Block

To display a Google Map in the front-end it is necessary that we load the Google Maps library and a script that uses it to build the map itself. This is extremely simple and if you have ever developed for WordPress, you should know how to do it.

The first thing we should do is create a script that can build a Google Map using the data we have put in the HTML. This script is in assets/src/js/public/public.js. Take a closer look to understand how it works:

  • In line 9 we search all the nodes that contain a map (filtering by one of the classes that we have included in the save method) and, for each of them, we call the initGoogleMap method.
  • This method relies on two functions to do its job. On the one hand, it extracts the coordinates of a possible marker with the function extractMarkerPositionIfAny of line 55 and, on the other, it extracts all the properties of the map (center coordinates, zoom level, list of visible buttons, etc) with the function extractMapOptions from line 26. Note that both functions are simply dedicated to reading the values of the attributes data-something we had put into the save method.
  • Finally, we created a map (line 18) and added a marker (line 21) using the Map and Marker classes, respectively, provided by the Google Maps library.

Now that we have this script, we only need two additional tweaks in our project:

Once all these changes have been made, this is the final result:

Google map with the Nelio Maps plugin in the front-end
Screenshot of a Google map with the Nelio Maps plugin in the front-end.

I know what you’re thinking: why, instead of doing all this by hand, didn’t we use the React component we had used in edit.js? Wouldn’t this save some time?

Indeed, using the React component we saw in the previous post would have saved us some trouble… but there’s a catch: it relies on React, which means we would have had to load React in the front-end to use too. And that seems like too much, don’t you think?

Pending Details

Finally, let me briefly discuss one aspect that’s very important, or else your plugin won’t work: the Google Maps API Key.

The Google Maps API Key

In order to use Google Maps you need to have an API key. How to get it is something Antonio explained to us a few days ago. Now, how do we use it?

One option would be to hardcode our API key in the plugin. If you’re the only one who’ll be using the plugin, that would do the trick. But if you plan on distributing your plugin to real users, it’s a very bad idea, because not all Google services are free—some are paid, and the costs can be quite expensive if everybody uses your key.

What to do in these cases? The idea is very simple: just add a configuration option in the plugin for people to enter their own API key.

In our case, if you add a map without API key, you will see the following warning message:

Warning message when there is no API key available
Warning message that is displayed to the user when there is no API key available.

urging you to add the API key.

Usually, you’d create a special page to manage your plugin’s settings. But for a plugin as easy and simple as the one we’re creating, I thought it be easier if we opted for a different solution.

In WordPress there is an options screen in /wp-admin/options.php that looks like this:

Option to enter the API key
How to add the API key from the WordPress settings.

It is a kind of “nice interface” to edit (almost) all the options that have been registered in WordPress and are in the table wp_options. So, all our plugin has to do is make sure that this option always exists in the database (even when there’s no API key set yet) and we will have a “nice interface” for the user to paste their API key without our doing anything!

To achieve this, use the init hook (see line 73 of this commit) with a function (line 134) that always sets a value to your key option. If the option does not exist yet, this function will set its value to the default value (an empty string) and save the option. If it already existed, the new value will be the same we already had, and so the update function won’t do anything. A clever and efective hack!

In Summary

In this post we have overcome the last barrier in our project: how to save the map and how to display it in the front-end. Basically, all we needed was a div with all the relevant information about the map (its center, options for displaying the buttons, the marker, etc.) and a small script to rebuild it in the front-end.

I hope that this tutorial has pleased you and serves as an example to undertake your own projects. As you can see, if you start a new project with a good foundation like the one we have created in Nelio with the boilerplate for Gutenberg development, materializing your ideas into real projects will be way easier.

If you have any questions, let us know in the comments section below. Good luck!

Featured image by Artem Bali on Unsplash.

PoorNot badGoodGreatExcellent (No Ratings Yet)
Loading...

How Combining Nelio A/B Testing and WPML Can Help You Increase International Customer Conversions

Published in WordPress.

If I asked you what is the first thing to do when trying to attract foreign clients to an online business, you might think the answer is obvious.

And it is. To sell to clients who speak another language you need to translate your website.

Not only is the answer simple, so is choosing the best way to do it. WPML is the most popular plugin for translating WordPress websites. And with good reason.

WPML comes with its famous Advanced Translation Editor to make translating quicker, is compatible with the most popular plugins and themes and is trusted by the most respected translation services.

The next step is to work out the best way to keep customers on your website to eventually make that all important conversion. By using Nelio A/B Testing you can quickly identify the best strategy for your different customers in each country. You can use Nelio A/B Testing to test your content, themes, widgets and pretty much anything else to see what works best for who.

Using Nelio A/B Testing and WPML plugins.
Screenshot of Nelio A/B Testing with WPML.

The good news is WPML and Nelio A/B Testing are completely compatible. Before we go through how you can use WPML and Nelio A/B Testing together to boost your international conversions, let’s look at why you need each plugin.

Why You Need to Translate Your Website for International Clients

When your clients are browsing your website you want to give them as many reasons as possible for them to make a purchase. Equally, you want to avoid giving them an excuse to not buy your product. A low hanging fruit which achieves both of these aims is translating your website to their native language.

Translating your website will build customers’ trust in your company as well as ensuring they feel comfortable using your pages. 72% of customers prefer to use their native language when shopping online. And while you might think the price is an important factor in making a purchase, 56% of consumers say that obtaining information in their own language is actually more important to them.

Clearly, one of the quickest and easiest ways to get customers on your side is by speaking their language.

Why Use WPML to Translate Your Website

WPML takes care of everything a business website needs to translate its website and welcome new clients:

  • Localize your website – You can use WPML to not only translate your content but to change your currency, translate all strings (site’s taglines, admin texts etc) and many other features. For example, Zespoke uses WPML to translate from English to German and change the currency from pounds to euros.
  • Quicker and higher quality translations – With WPML’s Advanced Translation Editor, you can translate content in less time than ever and more accurately.
Translating repeated texts.
  • Multilingual SEO – WPML will ensure you rank highly on Google searches in other languages by updating Hreflang links, organizing your languages on different pages and facilitating high-quality translations.
  • Partnership with major translation services – WPML is fully integrated with major translation services around the world. This means they are able to provide your high-quality translations quickly and pain-free.
  • Compatible with plugins – From Yoast to Elementor, WooCommerce and many others, WPML works seamlessly with the plugins which you need to run your business.

Why A/B Testing Is Important For Your Business

Once you have translated your website you are still left with an important question. How do I know what content will actually increase my sales in a particular country? The best way to find out is through A/B testing.

Despite the A/B testing myths you might have heard, A/B testing is a risk-free way to try out different marketing and advertising methods to see which one is the most effective with your particular audience. Perhaps you need to change your headings? Or you need a different theme? Or simply a different image? With A/B testing you can test all of these out and more.

By split testing, you can use your data to your advantage. You can add changes, measure the results and better understand what works and doesn’t work with your customers. The end result is increased conversions.

Why Use Nelio For Your A/B Testing

If you are using WordPress for your business then Nelio A/B Testing is the best way to increase your conversions through split testing.

  • Test everything: Whether it’s pages, posts, custom types, widgets, themes, heatmaps or anything else you can test it with Nelio A/B Testing.
Heatmap Example
Heatmap Example
  • Do everything on WordPress: By using Nelio you can carry out all of your testings without having to leave the WordPress admin.
  • Compatible with WordPress hosting providers: Nelio’s flexibility means you can use it with the most popular hosting providers including WPEngine, Kinsta and Pagely.
  • Instant updates: As soon as you find your winning formula you can automatically update your pages.

How WPML and Nelio A/B Testing Work Together

You can combine WPML and Nelio A/B Testing to split test your translated pages. The best part is it’s as easy as split testing a non-translated page.

Let’s imagine that you have a real estate website in English which you have translated into French. You now want to see which headline works best on your French translation.

Here is one of our real estate posts in French:

French ad for sale a house.
French ad for sale a house.

On your WordPress dashboard, all you need to do is:

1. Head to the French language section of your website by clicking the French flag.

2. We can now follow the normal split testing instructions as we would on a non-translated page.

3. In the Nelio A/B Testing -> Experiments click Add New and then Add custom post type experiment.

4. Fill out the basic information for your Experiment including the Name, Custom post type and Original custom post.

Custom post type experiment with Nelio A/B Testing
Adding a Custom Post Type Experiment with Nelio A/B Testing.

5. We now want to create an alternative page for our French real estate page. We will add a Name for the alternate page, add the Source (the link to the original page) and then click Create to create our new page

6. Once we name our page, we can click Save Experiment and edit content to start editing it.

7. We can now change the title of our testing page. Let’s try Maison contemporaine avec piscine.

New version of the ad
New version of the house ad created with Nelio A/B Testing.

8. Now that you have defined your experiment and created your page, you can head to Experiments find it and click Start.

Now that our test is up and running we can keep track of our results in the Dashboard.

Showing the results of the experiment
Showing the results of the experiment after its creation.

Try WPML and Nelio A/B Testing Together

You can now try WPML with Nelio A/B Testing out for yourself. Download WPML today to start the process of welcoming new customers from around the world.

Have you already used both plugins to A/B test your translated pages? Let us know how it went in the comments below!

Featured image by Duangphorn Wiriya on Unsplash.

PoorNot badGoodGreatExcellent (No Ratings Yet)
Loading...

Gutenberg Development with Examples: Google Maps (part 2)

Published in WordPress.

Hi there! We’re back with our tutorial to develop in Gutenberg. Last week we started a project that added a map block in WordPress. In that first post we defined what the requirements that our plugin has to meet were and we prepared the skeleton of what will end up being the final product, starting with the fantastic plugin boilerplate that we have created at Nelio.

Today comes the second part of the tutorial on how to create the map block. In this post we will see how to add a Google Maps map inside the WordPress editor and how to implement a user interface that allows us to manipulate its behavior.

A Quick Look at the Current Status of the Project…

In the current state of the project we have a simple Demoblock defined in packages/blocks/demo/. This small block is the one that comes as an example in Nelio’s plugin boilerplate and looks like this:

Demo block that our boilerplate includes by default in the block editor.
Demo block that our boilerplate includes by default in the block editor.

Obviously, this isn’t what we want. We’re not interested in a heart icon followed by some text, but in something like this:

Nelio Maps screenshot
Screenshot of the map block included in Nelio Maps.

That is, we want a Google Map block with an optional marker in it. How can we move from the original example block that our boilerplate had to this other, more powerful block? Well that’s what we’re going to answer today!

But before that, let me invest a couple of minutes explaining what we have right now and how we’re going to move forward. I think that, if you understand the current state of the project, you’ll have an easier time following what will come next.

Understanding the Demo block…

As I’ve already said, the demo block is defined in packages/blocks/demo/. In this folder you’ll find the styles of the block, its icon, and several files with the code that implements its operation. Let’s see the most important files.

On the one hand, there’s the main file: index.js. This file exports three variables: the name of the block (name), the definition of the block (settings), and the styles that the block supports (styles). These three variables are those used in packages/blocks/index.js to register the block in Gutenberg (with registerBlockType) and thus make it available to final users.

This main file, then, serves as an entry point to understand the block we are creating. In the object settings (settings), we see three important properties: attributes, edit, and save. Each of these properties has its own JavaScript file (for the sake of simplicity and ease of understanding), each named after their corresponding property. Let’s take a quick look at all of them:

  • The attributes.js file defines all those properties of our block that are dynamic and, therefore, should be tweakable by our users. In the case of our Demo block, the only attribute that exists is the text the user has written, but the map block will have many more options: the coordinates of the center of the map, the default zoom level the map should use, what buttons (if any) should be visible to interact with the map, etc.
  • The file edit.js is the one that defines how the block is displayed in the WordPress editor and what settings are offered to the user (both in the toolbar and in the sidebar of the block’s settings). In Demo, the edit simply includes the RichText component of WordPress to write the content. As we will see, the map block will be more complex and will also include additional settings.
  • Finally, save.js defines the method that will convert the block we were editing in Gutenberg into the HTML that must be rendered in the front-end. Again, in Demo we see that this function simply saves the contents of a RichText using RichText.Content, but it could be anything else (as we will see next week in the third and last part of this tutorial).

Creation of the Map Block Based on the Demo Block Included in the Plugin Boilerplate

Once we understand exactly how the Demo block works, it’s time to ask ourselves: how do we create ours? Well, very easy: as Toni told us a few days ago, we simply have to duplicate the directory packages/blocks/demo/ into packages/blocks/nelio-maps/ and start to modify everything necessary. I know, it’s easier said than done.

Let’s start with something easy: attributes.js. This file contains all the properties that should be modifiable by our final users. In the previous post we specified what requirements our plugin should meet and, therefore, we outlined what things should be tweakable. Well, taking a look at the resulting attributes.js you’ll clearly see what can be tweaked from our map block: zoom level, map center, visibility of different buttons… Super simple stuff!

The next point to modify is all that concerns the edition of the block in Gutenberg. To do this, we must dive into edit.js. If you look closely, you will see that it is not much more complicated than what we had in our original Demo block.

The most important thing is in the block’s render method (line 33), where we retrieve the attributes we just defined from an object named this.props. We’ll use this properties to render the block and its setings, of course. This is what we have:

  1. A toolbar ToolbarControls (line 66), which we defined in an external file named toolbar.js (don’t worry, we’ll see its content in a minute).
  2. The block settings that appear in the editor’s sidebar (line 68), which we find in a component called Inspector that we defined in inspector.js.
  3. The content of the block itself, which has two states:
    • If I do not have a Google Maps API key available, we show a user notice (line 122).
    • If we have this key, we show the map using MapBlock (line 83). The map might include a Marker (line 97), which is only visible when the option is activated, and might also be accompanied of a div (line 104) with additional information about it.

Google Maps as a React Component

If we want to put a Google map in our editor, we must use a component that allows us to use the Maps API of Google Maps. Considering that Gutenberg is built on top of React, the logical thing to do is to find out if there’s a React component of Google Maps. And, sure thing, there’s one!

As you can read in the project’s documentation, first we have to add the component into our project. Just install and add the dependency running the following command:

npm install react-google-maps --save-dev

which adds a new entry in our package.json and downloads the package into node_modules.

How to Create a WordPress Component that Encapsulates a React Component

If we continue looking at the documentation of this React project for Google Maps, we will see that they recommend us to wrap their GoogleMap component with our own component. Once it’s encapsulated, we will have to use our component in our plugin.

Well, let’s follow their lead and create a component called MapBlock in its own file map-block.js. And that’s it! We now have a map component ready that we can use in our Gutenberg block.

How to Add Block Settings in WordPress Editor’s Inspector

The next step is to configure how this map should look in the editor and add a few settings to tweak its appearance. To do this, we must add several settings sections in the Gutenberg sidebar. As I have already advanced, we achieve this with a component that we have called Inspector and that we have defined in the file inspector.js.

If you take a look at this file, you will see that it follows the same pattern as always: we are defining a Component with a render method. This method pulls the relevant attributes in this.props and returns the JSX with all the controls. In this particular case, it returns an instance of InspectorControls (this tells WordPress that this content goes to the sidebar) with several PanelBody sections. Let’s see each section in detail.

Basic Map Settings

The first PanelBody we found (line 47) has no title and, therefore, always appears as a section that can not be closed:

Basic adjustments of Nelio's map
Basic settings of the map block of Nelio Maps. Choose the size and zoom level with these two selectors.

The section defines a pair of RangeControls, whose result you can see in the previous screenshot. These two controls allow us to modify the height of the map and its zoom level.

Another interesting and simple section is the one found on line 121. Here we add a few options to activate or deactivate the buttons that should be shown on the map when displayed in the front-end :

Map buttons
Set which map buttons will be visible in the front-end.

To do this, we simply have to use the default WordPress component CheckboxControl.

How to Add a Custom Style Section for Our Map Block

Another interesting section of our block is the style section (line 68). You can see the final result in the following screenshot:

Google Maps Styles
You can change the appearance of the map using the Styles section in the block configuration.

It’s a special section because the component we use (MapStyles) is not something that exists in WordPress by default, but something we have created for this block in particular. As you can see in the previous link, it is a component that loads a set of predefined styles in a component of type ImagePicker (which, incidentally, does not exist by default in WordPress either—you can find it in packages/components/image-picker/).

When the user selects any of the styles included in ImagePicker, the MapStyles component invokes the onChange function it’s been given (see line 76 of inspector.js) passing two values: the name of the selected style and the associated JSON.

Finally, notice that one of the options that MapStyles includes is a Custom style:

Custom map style in Nelio Maps
In addition to the 5 default styles included in the block, there is the possibility to add your own style of the map using a JSON.

When selected, the component renders an additional text box (line 45) so that the user can enter their own style in JSON format. In case you did not know, the maps of Google Maps can be customized a lot!

How to Add a Marker into Our Map

The next section we have is the one that controls our marker (line 81). This section allows us to show or hide the marker (line 86) and, when active, gives us some additional settings:

How to add a bookmark to the map
The block allows you to add a marker to the map to indicate a specific point of the same.

As you see, a search box appears to search for locations in Google Maps (which we have implemented, again, with a custom component called AddressSearch) and the ability to show or hide the text block in which to put additional information about the marker .

By the way, notice that the AddressSearch component is based on a component called StandaloneSearchBox, which is also part of the React project . What a pleasure it is to reuse the work of others!

How to Configure the Toolbar of a Block

The last thing we have to discuss is the toolbar. If you have understood how the sidebar works, the toolbar is a piece of cake.

Nelio Maps toolbar
The toolbar offers quick access to the most important options on the Nelio Maps map.

The toolbar of our plugin is represented by the ToolbarControls component defined in toolbar.js. Here we simply add a component to define the alignment of the block (BlockAlignmentToolbar, on line 42), a pair of dropdowns to center the map (line 50) and to modify the location of the marker (line 79), and a couple of extra buttons to change the location of the text box in which we can put additional information about the marker (lines 107 and 120).

Search for locations integrated in WordPress
With integrated location search, you can search for any business or address without leaving the block editor.

In Summary

Today we have seen how to create the entire editing interface of our map block. As you can see, it’s a process that might seem complicated at first glance, but becomes pretty natural quickly. In the end, the secret is to start from an example that is well organized (as our plugin boilerplate is) and build the interface step by step, reusing the components that WordPress offers or that already exist, or even creating your own.

See you next week with the last part of this tutorial, where we’ll see how to save our map and how to view it in the front-end.

Featured image by rawpixel on Unsplash.

PoorNot badGoodGreatExcellent (No Ratings Yet)
Loading...

Gutenberg Development with Examples: Google Maps (part 1)

Published in WordPress.

A few days ago we published a new plugin in the WordPress.org plugins directory: Nelio Maps. As the name reveals, it’s a maps plugin that adds a new type of block in the WordPress editor. With it, we can easily add a Google map on our pages or posts. Here’s how it looks:

The Nelio Maps plugin allows you to insert and customize a Google Map to your pages and posts.

Nelio Maps is one of our first plugins entirely designed for Gutenberg. Despite being a relatively simple plugin, it is a very useful product. On the one hand, because any user who wants to add maps to their website can now do so by installing a simple and lightweight plugin. On the other hand, because any developer that wants to develop in Gutenberg now has a real example of how to create a plugin “from scratch”, simply by reading this post.

As I am aware that the development of a plugin like this is not the easiest thing in the world, I have organized this tutorial in three different parts. Today I will explain how to create the plugin “from scratch” so that we end up with the skeleton we’ll use to build the final product. In the second post I will explain how to get an interactive map in the WordPress block editor and we will see all the components that I have created to make the plugin. Finally, in the third and last post we’ll see how to save the map in the database and how we can show it in the frontend.

Defining our Project and the Plugin We Want

It may seem like a truism, but before embarking with any new project, the first thing we must do is define what we want to achieve with said project. Depending on the functionalities we want to include, we will have a different set of requirements. So let’s define what kind of map plugin we want to implement in this tutorial.

These are the requirements of the project:

  1. One should be able to add a map (or more than one) to their pages or posts.
  2. It should be possible to center the map anywhere by
    • either dragging the map with the mouse
    • or looking for the location in a search box.
  3. The size of the map should be adjustable, both in width and height
  4. The map should include different styles (black and white, custom color palettes, etc.)
  5. The user should be able to add a marker in the map.
  6. If there is a marker, the map must be accompanied by a text box with additional information about the marker.

Ambitious, right? Well, let’s get started!

How to Create a Gutenberg Plugin “From Scratch”

If you follow our blog, you’ve probably seen that a few days ago Antonio published a post explaining how to create plugins using a plugin boilerplate that we have created in Nelio. If you have not read his post yet, I recommend you read it first, because our plugin will be based on the plugin boilerplate wp-beb that Antonio explains there.

To start our project, the first thing we will do is mirror Nelio’s boilerplate plugin. First, create a new repository in your GitHub account. Then, follow the steps described in Github’s help pages to mirror our boilerplate:

git clone --bare https://github.com/avillegasn/wp-beb.git
cd wp-beb.git
git push --mirror https://github.com/your-username/your-repo.git

Once your project is ready, follow the instructions found in README.md to compile the project and thus be able to see it in your WordPress site.

How to Transform the Plugin Boilerplate into Your Plugin

As it appears in the plugin boilerplate documentation, the first thing we have to do is change the project’s name in the source code. That is, you have to change all occurrences of wp-beb (both uppercase and lowercase, with hyphens or underscores) by the name of our plugin (in my case, nelio-maps).

For this, we can use the following script:

Just keep in mind you’ll have to replace the string nelio maps int lines 5, 8, 9, and 10 to whatever your plugin’s name will be.

On the other hand, now is also a good time to change the plugin documentation. On the one hand you have to edit the files README.md and readme.txt to reflect the purpose of your new plugin (without forgetting to mention the fact that you are using our boilerplate as a base, of course). On the other, you should change the first comment in the main PHP file, as it’s the data WordPress uses to display the plugin in the Plugins screen.

You can see how I made all these changes in the first commit of the Nelio Maps project.

How to Clean the Plugin Boilerplate of Unnecessary Stuff

Nelio’s boilerplate plugin includes, by default, a couple of components: (a) a demo block and (b) a Gutenberg plugin. Since we are only interested in creating a block (the map), we are going to eliminate everything that is left over (the Gutenberg plugin).

This step is quite simple, since basically it is based on “deleting” unnecessary things from the plugin. Specifically, we should:

  1. Get rid of all the content that appears in the assets folder (which is where the Gutenberg plugin was added, its style, and its icon).
  2. Clean the file webpack.config.js, since there are a couple of rules that used the files in assets we just removed.
  3. Clean the main file of the plugin, since it enqueues a stylesheet and a JavaScript file that no longer exist.

You can see all the changes in this commit. If you compile the code again, you will see that the Demo block still exists, but the Gutenberg plugin that appeared in the upper right corner of the screen doesn’t.

Summary

In today’s post we have seen how to create a plugin for Gutenberg. First, we have defined the type of project we want to create and we have identified its requirements. Next, we have seen the steps needed to adapt the boilerplate plugin from Nelio to a new project. That is, we have seen how to clone Nelio’s boilerplate project and clean it to meet our particular needs.

See you next week with the second part of this tutorial, where we will modify the Demo block so that it performs all the functions we have described at the beginning of this post.

Featured image by Brett Zeck on Unsplash.

PoorNot badGoodGreatExcellent (No Ratings Yet)
Loading...

Translate your blocks with Nelio Translate for WordPress

Published in Inside Nelio.

In this blog we write content quite frequently. Our readers are used to this and, even though we are a small team, we can achieve our editorial goals thanks to Nelio Content, our editorial plugin for WordPress.

However, there is a task in our content generation process that is still dead boring and that Nelio Content does not solve: translating the contents from Spanish to English.

As we live in a global environment, we want our content to be available in both languages to cover as many readers as possible. We usually write our contents in Spanish and then translate them into English. And this translation work is done manually. Or it was, because we’ve finally fixed the inefficiency of this process.

Nowadays, translating texts by hand make us feel a bit like ancient humans. That is why we have fixed our process and now we are more efficient.

With the release of the block editor for WordPress we have created Nelio Translate, a plugin that translates the content of the blocks automatically with the help of Google Translate. And today we are going to talk about it.

Translating the content of WordPress blocks

Surely you think that translating content is quite easy: just copy the content of the editor, paste it into Google Translate (or your preferred translator), translate it, and then bring the translated content back to the WordPress editor. And that’s what we used to do with the classic editor! Well, that and a manual review of the translate text, as automatic translators are not infallible… 😉

Anyway, this solution became inefficient when the WordPress blocks editor appeared, because the process of copying and pasting in Gutenberg must be done block by block. That is, we can’t translate the content all at once. If you don’t believe me, give it a try and you will see that the pasted translation is broken, some blocks are missing, etc.

This situation opened our eyes and made us try to find a solution to this problem. And that’s how Nelio Translate was born.

Nelio Translate is our plugin to translate the contents of the Gutenberg blocks in WordPress.

First, you’ll need to install our plugin in your site. Get it here and install it on your WordPress as you would do with any other plugin.

When you want to translate a block in Gutenberg, you just have to select it and access the translation section in the right panel (where the block options are). There, select the source language (optional) and the target language and click on the translation button. This will translate the contents of the block.

Nelio Translate includes an additional option in your blocks that allows their translation, creating a new block with the translated content or replacing the original block with the translation.

In Nelio Translate’s settings screen (placed in the Settings menu of your WordPress) you can decide whether to duplicate the original block with the translated content (appended next to the original block) or replace the original block with the translation.

Another thing you should know is Nelio Content needs an API Key for Google Translate. Getting your API Key is not complicated if you follow the steps I explained in a previous post. And if you think we should make Nelio Translate compatible with other translation systems besides Google Translate, let me know by commenting down below.

Nelio Translate is compatible with the set of blocks that are included by default in the Gutenberg block editor in WordPress. If you use additional blocks, you can extend the plugin with your own code to make those blocks translatable, or contact us to discuss their inclusion in the translation process (something that shouldn’t be very difficult if the blocks were properly implemented by their developers).

On the other hand, if you want to translate the entire document at once instead of going block by block, you can also do it with Nelio Translate. In the block editor you will see the translation icon to the right of the publish button. Open that section and you’ll see the button that translates the whole document. Click on it and all the blocks that appear in your editor will be translated at the same time. This is the process we now follow to translate our posts into English.

Nelio Translate allows to translate all the blocks of the editor at once. This way, if you want to translate all the post you don’t have to do it block by block manually.

With Nelio Translate, our efficiency in generating content in more than one language has increased dramatically. Knowing that with just one click you have all the content translated and that the only thing you have to do is fix the small errors in the translation is a luxury for WordPress writers using Gutenberg.

I encourage you to try Nelio Translate, because if you are in a situation similar to ours where you have to translate content regularly, the time that you are going to save thanks to not having to go copying and pasting contents from here to there justifies its acquisition.

Featured image by Jason Leung on Unsplash.

PoorNot badGoodGreatExcellent (No Ratings Yet)
Loading...

5 JavaScript Features You Must Know to Develop in Gutenberg

Published in WordPress.

In 2016 Matt Mullenweg told us:

I’m going to give you some homework: learn JavaScript deeply (…) because it’s the future of the web.

Matt Mullenweg (on YouTube)

I don’t know if you followed his advice three years ago, but if you didn’t, you can’t postpone it anymore. The official release of the block editor has forced many developers to get up to speed with JavaScript. The language is becoming more and more relevant within WordPress and, if we do not want to stay behind, we must improve our skills with it.

In the past I wrote a post about what you can achieve using vanilla JavaScript, without libraries like jQuery. Today I want to go a step further and explain some of the novelties that are in the new versions of JavaScript and that are shocking the first time you see them. I think it’s important that you know them, because they’re present in all new JavaScript projects (including Gutenberg, of course).

Let’s learn JavaScript with Gutenberg!

#1 – Destructuring Objects and Arrays

Let’s suppose we want to see how the interface of editing a paragraph in Gutenberg works. If you’ve read our previous posts on Gutenberg, you know we have to look at the edit component of the relevant block. In our case, this component is ParagraphBlock and the first thing we’ll find in its render method, line 127, is this:

What is all this? Well, let’s start with something easier. Imagine you have an object like the following:

Destructuring objects and arrays makes it possible to unpack values from arrays, or properties from objects, into distinct variables:

With a single statement, we were able to recover the id, title, and content of our post. And this is precisely what Gutenberg was doing in our first snippet: we pulled the attributes object, the setAttributes function, the isRTL attribute, etc. of this.props.

A little more confusing, but equally interesting, is the possibility of extracting attributes from nested objects. That is, starting from an object such that:

we can retrieve values in post as well as values in a nested object, such as id or name in author:

Now pay attention: every time we destructure an object, the variables we create have the same names as the attributes we’re pulling. This begs the question: what would happen if we want to recover multiple id attributes from different nested objects? For example, in our case, both the post and its nested object author have an id, so…

can we pull these two values out? The solution lies in aliases:

That is, we can specify the attribute we want to pull (for example, author.id) and the name of the variable that will hold its value (authorId) all at once.

Finally, let me tell you that destructuring also works with arrays:

as well as function parameters. That is, if one of the parameters in our function is an object, we can destructure it in the function definition itself:

Pretty handy, huh?

#2 – Arrow Functions

Another fairly common example. If you take a look at captions the Gutenberg image blocks, you’ll see the following on line 693 :

What is the value in parentheses? Why is there an arrow? What is that about setAttributes with curly braces inside? Argh!!

Well, let’s decrypt this step by step. When you see an arrow like =>, you just met an arrow function. An arrow function can be extremely similar to classic functions, but they use a slightly different syntax:

The main advantage of arrow functions is that they can be further simplified, making the code even more compact. For example, if your function has a single instruction, you can save the curly braces and the return keyword, since the function will automatically return the result of evaluating its only statement:

Another simplification that we can make are the parentheses in its argument list. If we are writing a function that has a single parameter, the parentheses become optional:

#3 – Spread and Rest Operators

Back to the paragraph block, take a look at line 64 :

What the heck?

Well, let me introduce you to the spread operator: ....

Spread syntax allows an iterable such as an array expression or string to be expanded in places where zero or more arguments (for function calls) or elements (for array literals) are expected, or an object expression to be expanded in places where zero or more key-value pairs (for object literals) are expected.

Let’s start with the simplest example. Suppose we have an array with a certain number of elements and we want to put it inside another array. We can achieve this with:

With it, we are “expanding” (hence the operator’s name) the elements of one array (list) within the other (result).

This also works with objects:

Now look at the following example (which is a copy of the Gutenberg example with which we have opened this section):

If I am expanding two objects that have properties in common, the resulting object will contain the union of properties of both objects and, for every “repeated” property, it will contain the value of the object on the right. Thus, for example, the title attribute that is repeated in both objects, contains the value of the object newAttributes, while the other attributes (author on the one hand and words on the other) appear in the result with the only values they could contain.

#4 – Template Literals

Template literals are widely used in Gutenberg. You can see an example in the following index.js, line 133:

Or, even more complicated, inline 136:

Template literals are string literals allowing embedded expressions. You can use multi-line strings and string interpolation features with them. They were called “template strings” in prior editions of the ES2015 specification. Here you have another example similar to the first one we’ve just seen:

Now, what was happening in the second example? Basically, we are creating an object with properties whose “names” are dynamic (some use a variable, other use template literals). Let’s see this with a shorter example:

Easier than you expected, isn’t it?

#5 – Bye bye for and while

Finally, I would like to end this post with a couple of functions that are very useful for working with arrays and with which you should already be familiar. Both can be found, for example, in the block of Gutenberg columns. Indeed, I am talking about map (line 136) and reduce (line 119). Let’s see what each of them is for and how you can use them.

The map method creates a new array with the results of calling a provided function on every element in the calling array:

Basically, it’s a method that runs through all the elements of an array (that’s the for statement) and applies a function in each element (the “body” of the classic for).

The reduce methodis very similar to map, but instead of returning an array whose elements are the result of applying a function to the original elements, it returns a single value. That is, a method that allows you to apply a function to an accumulator and to each value of an array (from left to right) to reduce it to a single value. For example:

Wrapping Up

As you can see, new versions of JavaScript add constructions that allow writing code more efficiently and comfortably, but its syntax can be confusing at first. I hope that today’s post has helped you understand what’s new in JavaScript and how to use its new structures and functions.

I really like the way JavaScript is evolving, as I think it allows you to write better and more readable code (once you know how to read it, of course). What do you think? After reading this post, are you already keen to “learn JavaScript deeply” once and for all?

Featured image by Ross Findon on Unsplash.

PoorNot badGoodGreatExcellent (No Ratings Yet)
Loading...

Protect your WordPress by hiding the REST API

Published in WordPress.

The WordPress REST API was introduced in the WordPress core at the end of 2016 with the release of WordPress 4.6. Like all the big changes that appear in the platform, the REST API generated controversy in some and indifference in others.

It’s even possible that you have no idea what it is, but if you have an updated version of WordPress (and you should) you are exposing many aspects of your website publicly through the REST API. Just append the fragment /wp-json/ to your domain name and visit this URL to see it with your own eyes.

Moreover, do the exercise of visiting the following web URLs and you may be surprised with what you’ll find:

  • mydomain.com/wp-json/wp/v2/users
  • mydomain.com/wp-json/wp/v2/posts

As a result of the first URL you will have a JSON with the data of the users of your web. Notice that user identifiers are included there, and this is something that people traditionally hide due to security issues and to prevent possible attacks.

The second URL shows us a list with the last posts. However, if you have protected content that only certain premium users of your website (in a membership site, for example) should have access to, it’s possible that you’ve been exposing this premium content through the REST API.

Let’s see how we can avoid compromised situations by being more aware of what we publicly expose through the WordPress REST API.

Show WordPress REST API Only to Registered Users

A solution that we can implement to hide the WordPress REST API is to prevent those users who are not registered on our website from accessing it.

To hide the REST API to unregistered users, we must add the following code in our WordPress. Remember that you can put it in the functions.php file of your theme or just develop a plugin for it (a much better option).

Once you have put this code in your WordPress, accessing a route of the REST API on your website while not logged in will result in an error message. Your content is now protected.

Show WordPress REST API Only to Administrators

Now imagine that what you want is that only users with the Administrator role in your WordPress can access the REST API. In this case, the code you have to use is the following:

Basically, we simply added a new check: current_user_can. If you want to check with a different role than the administrator, you just need to make the corresponding change in this function.

If you can think of a better way to avoid accessing the WordPress REST API, or in your case you do it differently, do not hesitate to leave a comment below ☺️

Plugins to Disable The REST API in WordPress

In case you want to make more complex changes, you have the possibility to use plugins to disable the REST API in WordPress.

There are several plugins that allow you to disable the REST API in WordPress, but the one I recommend is Disable REST API by Dave McHale.

The Disable REST API plugin for WordPress allows you to have more control over which routes are active and which are not.
The Disable REST API plugin for WordPress allows you to have more control over
which routes are active and which are not.

By default, this plugin already prevents unregistered users from accessing the REST API of your WordPress. And in addition to it, the Disable REST API plugin allows you to select which API routes are active and which ones you want to disable on your website.

This way, controlling which data and information is public on your website through the WordPress REST API is tremendously simple.

Featured image by Ben Hershey on Unsplash.

PoorNot badGoodGreatExcellent (No Ratings Yet)
Loading...

The WordPress Block Editor Plugin Boilerplate

Published in WordPress.

The development in WordPress is being modernized by leaps and bounds. A few days ago I explained the current technologies that are already present in version 5 of our content management system. Now it’s time to teach you how to develop plugins for WordPress taking into account the possibilities of the new block editor.

Today I’ll describe the boilerplate that we are using in Nelio for our WordPress developments with a JavaScript base.

You have all the codebase of our boilerplate plugin for WordPress in GitHub, so you have no excuse to not modernize and expand your horizons as a developer.

WordPress Block Editor Boilerplate

The main reason for creating a project that serves as the basis for the creation of new WordPress plugins arises from our own need as developers to be able to unify and standardize all our projects.

The development in WordPress is no longer just PHP. Let's leave the antiques behind because it's time to modernize.
The development in WordPress is no longer just PHP. Let’s leave the old stuff behind because it’s time to modernize your skills.

Inspired by the WordPress Plugin Boilerplate, our idea is to do something similar but focused on plugins that extend the block editor with a modern stack using compilers, transpilers, bundlers and, ultimately, common development tools for JavaScript projects.

Installation And Development Process

The plugin boilerplate that we have created as a base can be downloaded directly from GitHub. After that, you can move it to the plugins folder (/wp-content/plugins/) of your WordPress installation:

git clone https://github.com/avillegasn/wp-beb.git

This will download the plugin folder with all the content. Then you need to rename both this folder and its content to use the name you want. For example, if your plugin is going to be called my-plugin:

  • rename the wp-beb files to my-plugin
  • replace wp-beb with my-plugin
  • replace wp_beb with my_plugin
  • replace WP_BEB with MY_PLUGIN

Once you have done this, to compile the plugin and generate the final code, run this:

npm install && npm run build

Keep in mind that you will need to have installed the following tools:

The npm install command downloads the dependencies of Node.js and PHP in the node_modules and vendor folders, respectively. When the process finishes you will have a dist folder with the compiled files. Now it is safe to activate the plugin in your WordPress.

In addition to the previous command, our boilerplate provides the following additional commands:

  • npm run dev Build files without minification.
  • npm run watch Build files and watch for changes.
  • npm run build Build files and minify JS and CSS.
  • npm run lint-php Run PHP_CodeSniffer on PHP files to detect errors.
  • npm run lint-php:fix Run phpcbf to try to fix PHP errors.
  • npm run lint-css Run stylelint on SCSS files to detect errors.
  • npm run lint-css:fix Try to fix errors on SCSS files.
  • npm run lint-js Run eslint on JS files to detect errors.
  • npm run lint-js:fix Try to fix errors on JS files.
  • npm run lint Run linting process on PHP, SCSS, and JS files.
  • npm run update:packages Update package dependencies in Node.js.

Usually you’ll be running npm run watch while you are developing code so that changes are compiled and bundled in real time. To generate a final, stable version, though, run npm run build.

Contents And Folder Structure

Our WordPress Block Editor Boilerplate includes the following files and folders:

  • .babelrc. Babel configuration file.
  • .editorconfig. EditorConfig file that helps maintain consistent coding styles for multiple developers working on the same project across various editors and IDEs.
  • .eslintignore. Used to exclude certain files from ESLint linting process.
  • .eslintrcESLint config file.
  • .gitattributesText file that gives attributes to path names in Git.
  • .gitignore. Used to exclude certain files from the repository.
    composer.json. Describes the PHP dependencies of the project and may contain other metadata as well.
  • composer.lock. Used to lock multiple developers working on the same project to the same versions of PHP dependencies.
    index.php. To hide the inner file structure in the server, whatever that be.
  • LICENSE.txt. Copy of the GNU GPL v2 license.
  • package-lock.json. Used to lock multiple developers working on the same project to the same versions of NPM dependencies.
  • package.jsonManifest file for the project. Central repository of configuration where you will find the names of the packages required and the CLI commands you can use to manage the project.
  • phpcs.ruleset.xmlPHP_CodeSniffer config file.
  • postcss.config.jsPostCSS config file.
  • README.md. The file that you’re currently reading.
  • readme.txt. The template for the WordPress plugin readme file.
  • webpack.config.js. Config file for webpack.
  • wp-beb.php. Main file of the WordPress plugin.
  • An assets directory that contains CSS, JS, and image resources.
  • languages directory that contains the translation files for i18n.
  • packages directory that contains block definitions to extend the WordPress block editor.

Apart from all this, once you compile the project, you will get the dist folder with the compiled files, the vendor directory with dependencies and executables for PHP, and the node_modules directory with dependencies and executables for NPM and JavaScript.

Add a New Block to The WordPress Block Editor

The interesting thing about this WordPress Block Editor Boilerplate is its default state. Once you have downloaded and compiled the plugin activate it and you’ll discover that it’s a fully functional plugin that adds a new block in your editor.

Demo block that our boilerplate includes by default in the block editor.
Demo block that our boilerplate includes by default in the block editor.

The Demo block added by our boilerplate is just a simple text block preceded by a heart dashicon, as you can see in the previous screenshot. The block also defines two additional styles, which modify the colors of the text inside the block. These should help you understand how to create blocks and styles in Gutenberg.

The JavaScript code that adds this block in the editor is in packages/blocks/demo (see here). If you want to delete this block, just delete the demo directory and delete its import and usage in the packages/blocks/index.js file.

In addition, the code for the demo block is split into different files, each of these including a different portion of the arguments used by registerBlockType.

On the other hand, if you want to add an additional block, duplicate the packages/blocks/demo and give it the name you want for your block. Modify the JavaScript files inside as you wish and remember to import the main file of the new block in packages/blocks/index.js.

Extend The Block Editor With a Plugin

In addition to the demo block that I mentioned before, our boilerplate for the block editor includes the definition of a Gutenberg plugin. Keep in mind that this “plugin” is not a regular WordPress plugin, but something that extends the block editor itself. “A plugin inside the WordPress plugin”, if you will.

Plugin for the block editor that we add by default.
Plugin for the block editor that we add by default.

You can see the plugin in the screenshot above, located on the right side. This plugin is activated by clicking on the icon on the top right, next to the publish button.

The plugin includes a color picker (so you can see how you can easily reuse the React components that Gutenberg includes) and a button to insert a demo block to the editor programmatically (another interesting scenario).

You have the plugin code in assets/src/js/admin (you can see it here). Specifically, the file plugin.js includes the call registerPlugin and the file plugin-component.js defines the component that is responsible for rendering the color picker and the button that I mentioned before.

Again, you can modify this plugin as you wish. Or you can delete it, if you want. To do so, remember to remove the plugin.js JavaScript file enqueued in the main file wp-beb.php (see here) as well as the corresponding CSS file (here).

Let’s Give it a Shot!

We hope that our WordPress Block Editor Boilerplate will help you to get rid of your JS fear and to start programming extensions for the WordPress block editor in a simple way. Try it and tell us about your experience. We will be happy to read your comments!

Featured image by Icons8 team on Unsplash.

PoorNot badGoodGreatExcellent (1 votes, average: 5.00 out of 5)
Loading...

Meet Our New Plugin: Nelio Maps. Insert Google Maps in Gutenberg Easily!

Published in WordPress.

Today I bring you good news: last week we published a new plugin on WordPress.org!

Nelio Maps allows you to add a Google map as a block in the WordPress editor. It’s the first plugin we’ve specifically designed and implemented for Gutenberg, and we hope users will fall in love with its simplicity and efficiency.

In this post I’ll showcase you the plugin and teach you how to use Nelio Maps to insert totally customized Google maps on your website. And if you are a developer, get ready, because in a couple of weeks I will share in detail how we’ve implemented this plugin in Nelio.

Installation of Nelio Maps

The first thing you must do to be able to use the new Nelio plugin is to install it on your WordPress. Luckily, this plugin is 100% free, so all you need to do is search for it in your Dashboard and install and activate it as always:

Installation of Nelio Maps
The installation of Nelio Maps follows the same procedure as that of any other plugin.

Once you have done it, you can go to the WordPress editor and add the new Google Map block that appears in the Extra section:

New block type: Google Map
After installing and activating Nelio Maps, a new type of block appears in your WordPress editor.

Unfortunately, if you add a map right now, all you’d see would be the following error:

Warning message when there is no API key available
Warning message letting you know that a Google Maps API Key is required.

Google Maps requires an API key to work so… let’s get one right away.

How to add a Google API Key to Nelio Maps

To use Google Maps in your WordPress you need an API Key, which will grant you access to the Google Maps API. Luckily, Antonio explained how to get a Google API Key, so simply follow his instructions on how to get your key and paste it in nelio_maps_api_key_option:

Option to enter the API key
How to add the API key from the WordPress settings.

Save the changes, return to your post or page, and voilà! your map is there with flying colors:

Appearance of a Google map by default
When you add a Google map to WordPress with Nelio Maps, its look and feel is sooooo “Google Maps”…

How to tweak a Google Map with Nelio Maps

With Nelio Maps, you are able to customize several aspects of the Google Map that you just added. To help you get familiar with the plugin, let me briefly explain all the settings it includes.

How to center the map at a specific point

The first thing you should know is that you can center the map at any exact location you might want. To center the map you have two options: either drag the map with the mouse and move it until you see what you want, or set the exact point using the location search box :

Search for locations integrated in WordPress
With the integrated location search, you can search for any business or address without leaving the block editor and center the map at the specific point you want.

How to modify the size of the map and its zoom level

Another option included in the plugin is the ability to change the size of the map. In this sense, you can tweak its height from 20% to 100% of the size of your screen. To do this, select the block and access the block settings that appear in the inspector area:

Basic adjustments of Nelio's map
Basic settings of the map block of Nelio Maps. Choose the size and zoom level with these two selectors.

On the other hand, you can change the block width using the usual alignment controls that already exist in other blocks. Specifically, you have three settings available: Align center, Wide width, and Full width :

Aligning a map
Nelio Maps allows you to use different alignments for your map, so the size it occupies on the screen can be adapted to your needs.

Finally, Nelio Maps also allows you to change the default zoom level used in your map. As you should have guessed from the previous screenshots, there are two ways to do it: either use the Zoom Level control in the sidebar or use the buttons on the map itself.

How to select which controls are available on the map

In the inspector area there’s a section called Map Options. There you will find several options to configure the map’s behavior as well as what controls the map should have. These settings are:

  • Show zoom buttons (to change the map’s current zoom level)
  • Show map type button (to switch between Map and Satellite)
  • Show fullscreen button (to toggle a fullscreen view of the map)
  • Make the map draggable (to drag the map around).
Map buttons
Set which map buttons will be visible in the front-end.

If you modify any of the previous settings, you will see that the map of the block editor doesn’t change. This is because these settings only modify the appearance of the map on the front-end. So, with the default options (that is, all options disabled), the map would look like this:

Default view of the map in the front-end
Default view of the map in the front-end, without any additional controls on it.

But if we enable all the checkboxes, now there are multiple buttons in the UI:

Map with controls
If you enable the different checkboxes, the user can interact with the map.

How to add a marker on the map

When we add a map on our website, we usually want to add a marker in it too. Well, you can do that with Nelio Maps, and it only takes two clicks! Simply expand the Marker section of the sidebar and activate the Marker in map option :

How to add a bookmark to the map
Add a marker to the map easily with Nelio Maps.

Once you have added the marker on the map, you can change its location using the search box that appears in the previous capture.

Moreover, notice that there is an extra option in the Marker section called Address Block. The address block is a small text area that overlaps the map and contains additional information about the marker. For example, you could use it to share the exact address that the marker points to and complement it with contact information:

Additional marker information
When you activate the marker, you have the possibility to write additional information about it in the overlapping text box.

You can align the box to either the left side or the right side of your map:

Aligning the marker text box
You can easily change the alignment of the marker text box.

or get rid of it completely, if you don’t want to use it.

How to change the style of the map

Finally, Nelio Maps includes a fantastic option to fully customize the appearance of your maps. By default, all the maps you add will have Google’s default style:

Well, in the block settings there’s a section called Style with several predefined map styles:

Styles of Google Maps
You can change the appearance of the map using the Styles section in the block configuration.

If you choose one of these styles, you will see that the map changes dramatically:

Nelio Maps screenshot
Screenshot of the map block of Nelio Maps, applying the Light style.

And you know what’s best? With Nelio Maps you don’t have to use any of the predefined styles if you don’t want to! Instead, there’s an option for you to create the style you want :

Custom map style in Nelio Maps
In addition to the 5 default styles included in the block, there is the possibility to add your own style of the map using a JSON.

Give It a Shot!

So, tell me, what do you think of the plugin? Do you like it? Do you have any suggestions? Whether you think it’s the best plugin in the world or if you think it can and should be improved, we’d love to hear.

So please leave a comment down below and we’ll see how we can make Nelio Maps the best and simplest maps plugin for Gutenberg!

Featured image of Anna Pascale in Unsplash.

PoorNot badGoodGreatExcellent (No Ratings Yet)
Loading...

Resources to Master the Technologies Behind Gutenberg For WordPress

Published in WordPress.

One of the biggest challenges developers have to face with WordPress is to recycle our knowledge to adapt to the new programming paradigm behind the new block editor. The main change with Gutenberg is the new stack of technologies used. Usually a WordPress developer created plugins using PHP mainly, with minor parts written in JavaScript. Now the key tool is JavaScript, leaving PHP as just a basis to create the structure of plugins and themes.

You may think that this is not the case and that PHP still has a long journey in WordPress. I do not blame you for it, as changes always are difficult to accept. However, I think you’re wrong. JavaScript is no longer the future of WordPress, but the present. And if you want to maintain your position, you’ll need to get up to speed with it right now.

Learn JavaScript deeply, as Matt said…

Fortunately, although they have insisted that we must learn JavaScript deeply, I think that is not the case. Knowing some minimums that any tutorial can teach you is more than enough. You can learn everything else you will need to start developing for Gutenberg quickly thanks to the resources that I will describe throughout this article.

Learn JavaScript

When you learn a new programming language, the first thing you need to know is to understand its syntax. Only in this way can you start programming with it. Once you do this, you have everything ready to start creating.

 When you want to learn JavaScript, you do not need to read a manual with more than 1000 pages... There are much simpler and more enjoyable options and at the same time they are sufficiently complete.
When you want to learn JavaScript, you do not need to read a manual with more than 1000 pages… There are much simpler and more enjoyable options and at the same time they are sufficiently complete.

If you have never done anything with JavaScript before, these are some tutorials in different formats that will help you get started:

  • JavaScript Language Basics: free course by Zac Gordon in video format.
  • JavaScript 30: learn by doing with a challenge every day for 30 days with Wes Bos in this free course.
  • A re-introduction to JavaScript: brief introduction to JavaScript by the guys at Mozilla.
  • JavaScript For Cats: another introduction to JavaScript with certain touches of cat humor.
  • Exercism.io: free web where you can do exercises in JavaScript and upload your solution for a mentor to evaluate it.
  • JSBooks: if you are one of those who prefer to learn with books, here you have a lot of them for free.

Conversely, if you already have some experience using JavaScript, expand your knowledge by studying advanced concepts about the functions, asynchronous execution with promises and async / await, and in short, everything related to ESNext.

With a day of JavaScript training should be more than enough to acquire the basic knowledge to move with ease in everything related to what you will need to develop on top of the WordPress block editor.

Learn React and Redux

In addition to JavaScript, to develop on the WordPress block editor you will need to have certain notions of React and Redux.

This is what everyone will tell you, but the truth is that it is not like that. You can develop for Gutenberg without having any idea of React or Redux. Of course, if you know how they work and what they are used for, then that would be better.

React and, above all, JSX

What you can not avoid is to know how the JSX syntax works to create elements within React, which we will use to define the interface of our components (whether they are Gutenberg blocks or views within the editor).

Imagine that you want to define the interface for the Product and ShoppingList components and then use them in a Gutenberg block. With standard notation you would do it in the following way, using the wp.element.createElement() function provided by Gutenberg:

On the other hand, if you use JSX within the render() method, which is nothing more than a notation similar to HTML, what you have is the following:

Using JSX simplifies writing and reusing components, since the code is much simpler and easier to read. As you can see, in the previous example we are creating React components without having any idea of React, by only knowing how to handle JSX and using it as if it were HTML with superpowers. In addition, you can also use existing components in Gutenberg. You can see them in this viewer that is also linked to the official documentation.

There is only one problem. You will need to transpile the code with Babel so that the JSX notation ends up transforming into regular code that any browser can interpret. However, this is not a drama since you can do it automatically by using WebPack.

Redux to Maintain The Status of Your Application

On the other hand, you probably heard about Redux. It’s a tool to save and manage the status in JavaScript applications. Again, if you’re interested in learning how to use it, I recommend these Wes Bos videos, but it’s not necessary either.

If you had the need to create your own data store, you would not do it with Redux, but you would use the @wordpress/data package included in Gutenberg. This package uses Redux internally, but that doesn’t matter. Also, we’re talking about a complex use case that you probably don’t need, at least in an initial stage. So for now forget about it.

NPM, WebPack, Babel, PostCSS, and ESLint

In addition to JavaScript and basic notions of React and JSX, for the new era that is already here in WordPress you will need to know the following technologies so that your developer tasks are much simpler and highly automated:

  • NPM: the dependency manager for JavaScript. Just define the dependencies that you need and install them by doing npm install.
  • WebPack: the JavaScript bundler. It is not easy to configure at the beginning, but once you have it, it facilitates the work of managing JavaScript files: transpilation, minification…
  • Babel: the JavaScript compiler to be able to use the syntax of the next versions of this language today.
  • PostCSS: the same as Babel, but for your CSS stylesheets.
  • ESLint: detects JavaScript usage and style errors so you can avoid them while you are writing code.

I already talked about most of these technologies here. However, I am going to write down another article soon, where I will explain how to integrate them into a WordPress development project so that you can use them in a real case.

How to Create New Blocks For Gutenberg

Now, let’s go for the most important part: what we need to start creating new blocks for the WordPress editor.

The first thing you need to start creating your own blocks is to master the function wp.blocks.registerBlockType() . You will find the most complete documentation on this function in the official Gutenberg guide.

The arguments for this function are a string with the name of the block, which must be unique, and an object with the configuration of the block, where the most important parts are the save and the edit functions of the block. I already briefly explained this to you in this article.

If this seems too complicated, you can start using Ahmad Awais toolkit called create-guten-block. This creates a folder structure with all the necessary dependencies to create your first block. You can see a tutorial on its use in the following video:

Finally, if this still seems too complex, you have one last option available. Surely you know the plugin Advanced Custom Fields (also known as ACF, for short). Well, this plugin will allow you to create blocks for Gutenberg without having any idea of JavaScript.

But I’m not going to explain it to you, I’ll let Mauricio Gelves do it. Go check his presentation on this subject in the WordCamp Zaragoza 2019 that you already have on WordPress.tv (in Spanish):

How to Extend the Block Editor in WordPress

There are many other things you can do with Gutenberg, in addition to creating new blocks. For example, you can create a plugin within Gutenberg to add a panel of options in the right side of the editor with everything you want. The best thing about this is that the official WordPress documentation includes this complete tutorial with concrete examples of what you can do there.

In addition to this, you can extend the WordPress editor by adding new styles to existing blocks, add more custom settings to the blocks, remove blocks or hide them, or filter the categories of blocks that you can have in the editor.

I recommend you take a look at the official documentation that you have in the Gutenberg handbook for developers and designers that you will find here. Take it easy because there is a lot of information and this is one of the best resources you have available.

Featured image by Christian Fregnan in Unsplash .

PoorNot badGoodGreatExcellent (No Ratings Yet)
Loading...