Schlagwort-Archive: Tutorial

WordPress Gutenberg Block API: Extending Blocks

Welcome back to our series on creating custom blocks with the WordPress Gutenberg Block API. This tutorial is all about extending the random image block we created in the previous post. We got as far as adding a drop-down control to select an image category. We’ll continue with this by adding more block options to allow further customization.

Specifically, we’ll see how to add block settings in various parts of the editor. That’s right, you’re not just limited to adding block controls directly on the block itself!

The final my-custom-block plugin code is available to download. Just click the link in the sidebar to the right and download the zip file to your computer, and install it as you would any other WordPress plugin. You can also find the source code in our GitHub repo.

Gutenberg development is cracking on at a fair pace, and there’s been a new significant release since the last tutorial was published. The version of Gutenberg used in this tutorial has been updated to 3.0.1, and some of the editor UI may look slightly different from screenshots shown in previous tutorials in this series.

Let’s Extend!

The drop-down control we added in the previous tutorial was located inside the editor, directly underneath the markup for the random image. This was convenient, but we have other choices too.

We can also add block controls to a pop-up toolbar (which appears when a block is selected) and a block inspector panel.

Block control locations

In the screenshot above, we can see the toolbar controls for the paragraph block [1], as well as the associated controls in the panel inspector [3]. Location [2] shows the drop-down control for our random image block.

You might already be thinking about which location you’d choose for your own block settings, but you don’t have to choose just one of these locations. They aren’t mutually exclusive. For example, for the paragraph block (shown above), you can see that the settings are split between the block inspector panel and the toolbar. 

Furthermore, it’s perfectly OK to have two separate controls in different locations in the editor that affect the same setting. You might not want to do this too often, but it’s useful to know how to implement it, so we’ll see how to do this a little later on.

Direct Block Settings

Let’s start with the easiest way to add functionality to your block, which is directly inside the block’s edit function. We’ve already used this approach to add our random image drop-down control because it requires very little extra effort.

We won’t go over adding new controls to the block itself, but we can tweak the behavior of the drop-down control to be a bit more intuitive. To make it render as close as possible to the front end, we can restrict the drop-down from appearing unless the block is selected.

Let’s make this change now. If you’re following this tutorial from last time then open up /my-custom-block/src/random-image/index.js in your favorite editor. This is the main JavaScript file for our random image block.

One of the props passed to all blocks is isSelected, which holds the status of the block’s visibility. We can use this to conditionally display the category drop-down control.

Firstly, pull out isSelected from the props object and add it to the list of constants inside the edit function. This is useful so we can reference it by a shortened name (i.e. isSelected rather than props.isSelected).

Next, we can use this property to determine if the drop-down control should be displayed:

This is a shorthand way of testing that isSelected is true, since we can’t use a full-blown JavaScript if statement inside JSX code.

Make sure you’re still watching files for changes so any block source code (JSX, ES6+, Sass, etc.) is transpiled into valid JavaScript and CSS. If you aren’t currently watching files for changes, then open a command-line window inside the my-custom-block plugin root folder and enter npm start.

Open up the Gutenberg editor and add the random image block. This time, the drop-down control isn’t visible if the block hasn’t been clicked yet.

Conditional Block Control

This gives the block a much more interactive feel to it.

Toolbar Controls

If you’ve used any of the core Gutenberg blocks (such as the paragraph block) then you’ll be familiar with toolbar settings. As soon as the Paragraph block is selected, a pop-up toolbar appears containing buttons for formatting the text. This type of control is great for block settings that have an on/off type state—for example, text alignment or formatting such as bold or italic.

We’ll use the built-in alignment toolbar control to allow the drop-down image category control to be left (the default), right, or center aligned.

First, we need to pull out the AlignmentToolBar and BlockControls components from wp.blocks. These allow us to show alignment controls inside a floating toolbar above our block when it’s selected. These are part of the core components we can use in our own blocks.

The BlockControls component acts as the toolbar container, and AlignmentToolbar is placed inside.

We still need to hook up the behavior of the alignment toolbar manually, which we can do by adding a new categoryAlign attribute to store block alignment status (left, right, or center).

Our attributes object now contains two settings.

The default for the categoryAlign attribute is an empty string, which will result in no alignment being applied by default.

To reference the new attribute, we can pull this value out into its own constant variable the same way we did for the drop-down category attribute.

All we need to do now is drop the two new components into the edit function and configure the properties.

As you can see all we needed to do was to assign the value attribute of Alignmenttoolbar to categoryAlign attribute and call the setAttributes function whenever a new toolbar button has been clicked. This function in turn updates the categoryAlign attribute and keeps everything in sync.

To apply the alignment style of the drop-down control, we need to add a style property to our form element.

Control Alignment

Note that we don’t need this control to affect anything on the front end, so we didn’t need to add any code to the block’s save function.

Adding a Settings Panel

The block inspector panel provides you with a large area to add block controls and is a great location for more complex controls.

We’ll focus on adding two drop-down controls to the inspector panel. The first one will be a duplicate of the category drop-down control to select the type of random image. This demonstrates how to have more than one control updating a common attribute.

When one control is updated, the corresponding one will automatically update too! In practice, though, you’ll usually only want one control per setting.

The second drop-down control will allow you to select the filter applied to the random image. The PlaceIMG web service supports two types of filter—grayscale and sepia—and we can select between them by simply adding sepia or grayscale to the HTTP request URL. If we don’t specify a filter then a standard colored image will be returned.

The code for the two drop-downs is pretty similar, so we’ll add them together.

First of all, let’s define the new blocks and components we need.

Here, the new variables are InspectorControls, PanelBody, PanelRow, and Fragment, which are all used to help create the inspector panel UI.

The <Fragment> component is very useful when you need to return multiple top-level elements from the edit or save functions but don’t want to wrap them in an element that will be outputted.

<Fragment> won’t output any markup at all on the front end and acts like an invisible container. It’s just a convenient way to return multiple top-level elements and is an alternative to the previous method of returning an array of elements instead.

We only need to add one new attribute called imageFilter as the existing category attribute can be reused.

Inside the edit function, we need to add a new variable with references to the new attribute.

Adding a block inspector panel is surprisingly easy. The component structure we’ll use is as follows:

The <InspectorControls> component acts as the block inspector container, and <PanelBody> defines individual collapsible sections. Inside each of these, you can have any number of <PanelRow> components, which in turn contain your controls.

We’ve already defined markup for our category drop-down control which we can reuse. To do this, abstract it out into a separate function:

This function can then be referenced whenever we need the category drop-down control rendered. The markup for the block inspector panel needs to be outside of the block markup, so we can use the <Fragment> component to wrap them both before they are returned.

Next, we need to add the block inspector components for the category and image filter drop-downs. These need to be defined inside <PanelRow> components, and we also have to define a new callback function to handle the onChange event. This is very similar to the category drop-down code from the last tutorial, so it should be familiar to you by now.

Putting this all together, the edit method’s return function now looks like this:

And the setFilter callback is defined as:

To get the filtered image, we need to update the RandomImage component to accept the new filter value every time the drop-down is changed.

Notice how we’re using this new component property in the edit method to send the new filter value to PlaceIMG.

All these code changes result in a new block inspector panel being created with two drop-down controls to change the image category and filter.

Block Inspector Controls

To get the new filter property working for the front end too, we just need to update the save method. 

Frontend Image Filter

Conclusion

In this post, we covered three different methods for adding settings to a block:

  • pop-up toolbar
  • directly on the block itself
  • block inspector panel

We only added basic settings for each block, but we could easily take this even further by adding support for multiple images, adding image captions, and controlling styles such as the border color, radius, or random image size.

I’m sure that by now you’ve probably got some ideas for creating your own custom blocks. I’d love to hear what kind of blocks you’d find useful in your own projects!

We’re just getting started with Gutenberg here at Envato Tuts+, so if there are any particular aspects of Gutenberg block development you’d like to see covered in more depth in future tutorials, please let us know via the comments.

from Envato Tuts+ Code – WordPress https://ift.tt/2HXKf6w

Advertisements

New Course: Coding Blocks for WordPress Gutenberg

Are you ready for WordPress Gutenberg? This dramatic redesign of the WordPress editor aims to provide a true WYSIWYG experience by breaking up pieces of posts and pages into individual blocks of content. 

In our brand new course, Coding Blocks for WordPress Gutenberg, you’ll learn how to create your own blocks to extend the functionality of the Gutenberg editor. 

Coding Blocks for WordPress Gutenberg

What You’ll Learn

In this step-by-step video course, Jeremy McPeak will show you exactly how blocks work in WordPress Gutenberg and how to write your own.

Among other things, you’ll learn how to:

  • define attributes to maintain state
  • build and refine the user interface for your block
  • store data
  • add rich text capabilities

Check out the quick intro video to get a better idea of what’s included, so that you can get fully up to speed with Gutenberg before it becomes part of WordPress core!

Watch the Introduction

//fast.wistia.com/assets/external/E-v1.js

 

Take the Course

You can take our new course straight away with a subscription to Envato Elements. For a single low monthly fee, you get access not only to this course, but also to our growing library of over 1,000 video courses and industry-leading eBooks on Envato Tuts+. 

Plus you now get unlimited downloads from the huge Envato Elements library of 550,000+ creative assets. Create with unique fonts, photos, graphics and templates, and deliver better projects faster.

from Envato Tuts+ Code – WordPress https://ift.tt/2JxDuy1

WordPress Gutenberg Block API: Creating Custom Blocks

The new WordPress editor (codenamed Gutenberg) is due for release in version 5.0. Now is the perfect time to get to grips with it before it lands in WordPress core. In this series, I’m showing you how to work with the Block API and create your very own content blocks which you can use to build out your posts and pages.

In the previous post, we saw how to use the create-guten-block toolkit to create a plugin containing a sample block ready for us to work with. We can easily extend this as required, but it’s a good idea to know how to create a block from scratch to fully understand all aspects of Gutenberg block development.

In this post we’ll create a second block in our my-custom-block plugin to display a random image from the PlaceIMG web service. You’ll also be able to customize the block by selecting the image category from a drop-down select control.

But first we’ll learn how block scripts and styles are enqueued before moving on to the all-important registerBlockType() function, which is fundamental to creating blocks in Gutenberg.

Enqueueing Block Scripts and Styles

To add the JavaScript and CSS required by our blocks, we can use two new WordPress hooks provided by Gutenberg:

  • enqueue_block_editor_assets
  • enqueue_block_assets

These are only available if the Gutenberg plugin is active, and they work in a similar way to standard WordPress hooks for enqueueing scripts. However, they are intended specifically for working with Gutenberg blocks.

The enqueue_block_editor_assets hook adds scripts and styles to the admin editor only. This makes it ideal for enqueueing JavaScript to register blocks and CSS to style user interface elements for block settings.

For block output, though, you’ll want your blocks to render the same in the editor as they do on the front end most of the time. Using enqueue_block_assets makes this easy as styles are automatically added to both the editor and front end. You can also use this hook to load JavaScript if required.

But you might be wondering how to enqueue scripts and styles only on the front end. There isn’t a WordPress hook to allow you to do this directly, but you can get around this by adding a conditional statement inside the enqueue_block_assets hook callback function.

To actually enqueue scripts and styles using these two new hooks, you can use the standard wp_enqueue_style() and wp_enqueue_scripts() functions as you normally would.

However, you need to make sure that you’re using the correct script dependencies. For enqueueing scripts on the editor, you can use the following dependencies:

  • scripts: array( 'wp-blocks', 'wp-i18n', 'wp-element', 'wp-components' )
  • styles: array( 'wp-edit-blocks' )

And when enqueueing styles for both the editor and front end, you can use this dependency:

  • array( 'wp-blocks' )

One thing worth mentioning here is that the actual files enqueued by our my-custom-block plugin are the compiled versions of JavaScript and CSS and not the files containing the JSX and Sass source code.

This is just something to bear in mind when manually enqueueing files. If you try to enqueue raw source code that includes React, ES6+, or Sass then you’ll encounter numerous errors.

This is why it’s useful to use a toolkit such as create-guten-block as it processes and enqueues scripts for you automatically!

Registering Gutenberg Blocks

To create a new block, we need to register it with Gutenberg by calling registerBlockType() and passing in the block name plus a configuration object. This object has quite a few properties that require proper explanation.

Firstly, though, let’s take a look at the block name. This is the first parameter and is a string made up of two parts, a namespace and the block name itself, separated by a forward slash character.

For example:

If you’re registering several blocks in a plugin then you can use the same namespace to organize all your blocks. The namespace must be unique to your plugin, though, which helps prevent naming conflicts. This can happen if a block with the same name has already been registered via another plugin.

The second registerBlockType() parameter is a settings object and requires a number of properties to be specified:

  • title (string): displayed in the editor as the searchable block label
  • description (optional string): describes the purpose of a block
  • icon (optional Dashicon or JSX element): icon associated with a block
  • category (string): where the block appears in the Add blocks dialog
  • keywords (optional array): up to three keywords used in block searches
  • attributes (optional object): handles the dynamic block data
  • edit (function): a function that returns markup to be rendered in the editor
  • save (function): a function that returns markup to be rendered on the front end
  • useOnce (optional boolean): restrict block from being added more than once
  • supports (optional object): defines block-supported features

Assuming we’re using JSX for block development, here’s what an example registerBlockType() call could look like for a very simple block:

Notice how we didn’t include an entry for the description, attributes, useOnce, and supports properties? Any fields that are optional (and not relevant to your block) can be safely omitted. For example, as this block didn’t involve any dynamic data, we don’t need to worry about specifying any attributes.

Let’s now cover the registerBlockType() configuration object properties in more detail one by one.

Title and Description

When inserting or searching for a block in the editor, the title will be displayed in the list of available blocks.

It’s also displayed in the block inspector window, along with the block description if defined. If the block inspector isn’t currently visible then you can use the gear icon in the top right corner of the Gutenberg editor to toggle visibility.

Block title and description

Both the title and description fields should ideally be wrapped in i18n functions to allow translation into other languages.

Category

There are five block categories currently available:

  • common
  • formatting
  • layout
  • widgets
  • embed

These determine the category section where your block is listed inside the Add block window.

Block categories

The Blocks tab contains Common Blocks, Formatting, Layout Elements, and Widgets categories, while the Embeds category has its own tab.

Categories are currently fixed in Gutenberg, but this could be subject to change in the future. This would be useful, for instance, if you were developing multiple blocks in a single plugin and you wanted them all to be listed under a common category so users could locate them more easily.

Icon

By default, your block is assigned the shield Dashicon, but you can override this by specifying a custom Dashicon in the icon field.

Dashicons

Each Dashicon is prefixed with dashicons- followed by a unique string. For example, the gear icon has the name dashicons-admin-generic. To use this as a block icon, just remove the dashicons- prefix for it to be recognised, e.g. icon: 'admin-generic'.

However, you aren’t just limited to using Dashicons as the icon property. The function also accepts a JSX element, which means you can use any image or SVG element as your block icon. 

Just make sure to keep the icon size consistent with other block icons, which is 20 x 20 pixels by default.

Keywords

Choose up to three translatable keywords to help make your block stand out when users search for a block. It’s best to choose keywords that closely relate to the functionality of your block for best results.

You could even declare your company and/or plugin name as keywords so that if you have multiple blocks, users can start typing your company name and all your blocks will appear in search results.

Although adding keywords is entirely optional, it’s a great way to make it easier for users to find your blocks.

Attributes

Attributes help with managing dynamic data in a block. This property is optional as you don’t need it for very simple blocks that output static content.

However, if your block deals with data that could change (such as the contents of an editable text area) or you need to store block settings, then using attributes is the way to go. 

Attributes work by storing dynamic block data either in the post content saved to the database or in post meta. In this tutorial we’ll only be using attributes that store data along with the post content.

To retrieve attribute data stored in post content, we need to specify where it’s located in the markup. We can do this by specifying a CSS selector that points to the attribute data.

For example, if our block contained an anchor tag, we can use its title field as our attribute as follows:

Here, the attribute name is linktitle, which is an arbitrary string and can be anything you like.

For example, we could use this attribute to store the link title <a title="some title"> that’s been entered via a textbox in block settings. Doing so suddenly makes the title field dynamic and allows you to change its value in the editor.

When the post is saved, the attribute value is inserted into the links title field. Similarly, when the editor is loaded, the value of the title tag is retrieved from the content and inserted into the linktitle attribute.

There are more ways you can use source to determine how block content is stored or retrieved via attributes. For instance, you can use the 'text' source to extract the inner text from a paragraph element.

You can also use the children source to extract all child nodes of an element into an array and store it in an attribute.

This selects the element with class .parent and stores all child nodes in the editablecontent attribute.

If you don’t specify a source then the attribute value is saved in HTML comments as part of the post markup when saved to the database. These comments are stripped out before the post is rendered on the front end.

We’ll be seeing a specific example of this type of attribute when we get into implementing our random image block later in this tutorial.

Attributes can take a little getting used to, so don’t worry if you don’t fully understand them first time around. I’d recommend taking a look at the attributes section of the Gutenberg handbook for more details and examples.

Edit

The edit function controls how your block appears inside the editor interface. Dynamic data is passed to each block as props, including any custom attributes that have been defined.

It’s common practice to add className={ props.className } to the main block element to output a CSS class specific to your block. WordPress doesn’t add this for you inside the editor, so it has to be added manually for each block if you want to include it.

Using props.className is standard practice and is recommended as it provides a way to tailor CSS styles for each individual block. The format of the generated CSS class is .wp-block-{namespace}-{name}. As you can see, this is based on the block namespace/name and makes it ideal to be used as a unique block identifier.

The edit function requires you to return valid markup via the render() method, which is then used to render your block inside the editor.

Save

Similar to the edit function, save displays a visual representation of your block but on the front end. It also receives dynamic block data (if defined) via props.

One main difference is that props.className isn’t available inside save, but this isn’t a problem because it’s inserted automatically by Gutenberg.

Supports

The supports property accepts an object of boolean values to determine whether your block supports certain core features.

The available object properties you can set are as follows.

  • anchor (default false): allows you to link directly to a specific block
  • customClassName (true): adds a field in the block inspector to define a custom className for the block 
  • className (true): adds a className to the block root element based on the block name
  • html (true): allows the block markup to be edited directly

The useOnce Property

This is a useful property that allows you to restrict a block from being added more than once to a page. An example of this is the core More block, which can’t be added to a page if already present.

useOnce property

As you can see, once the More block has been added, the block icon is grayed out and can’t be selected. The useOnce property is set to false by default.

Let’s Get Creative!

It’s time now to use the knowledge we’ve gained so far to implement a solid working example of a block that does something more interesting than simply output static content.

We’ll be building a block to output a random image obtained via an external request to the PlaceIMG website, which returns a random image. Furthermore, you’ll be able to select the category of image returned via a select drop-down control.

Our random image block

For convenience, we’ll add our new block to the same my-custom-block plugin, rather than creating a brand new plugin. The code for the default block is located inside the /src/block folder, so add another folder inside /src called random-image and add three new files:

  • index.js: registers our new block
  • editor.scss: for editor styles
  • style.scss: styles for the editor and front end

Alternatively, you could copy the /src/block folder and rename it if you don’t want to type everything out by hand. Make sure, though, to rename block.js to index.js inside the new block folder.

We’re using index.js for the main block filename as this allows us to simplify the import statement inside blocks.js. Instead of having to include the path and full filename of the block, we can just specify the path to the block folder, and import will automatically look for an index.js file.

Open up /src/blocks.js and add a reference to our new block at the top of the file, directly underneath the existing import statement.

Inside /src/random-image/index.js, add the following code to kick-start our new block.

This sets up the framework of our block and is pretty similar to the boilerplate block code generated by the create-guten-block toolkit.

We start by importing the editor and front-end style sheets, and then we’ll extract some commonly used functions from wp.i18n and wp.blocks into local variables.

Inside registerBlockType(), values have been entered for the title, icon, category, and keywords properties, while the edit and save functions currently just output static content.

Add the random image block to a new page to see the output generated so far.

Bare bones block output

Make sure you’re still watching files for changes so any block source code (JSX, ES6+, Sass, etc.) is transpiled into valid JavaScript and CSS. If you aren’t currently watching files for changes, then open a command line window inside the my-custom-block plugin root folder and enter npm start.

You might be wondering why we didn’t have to add any PHP code to enqueue additional block scripts. The block scripts for the my-custom-block block are enqueued via init.php, but we don’t need to enqueue scripts specifically for our new block as this is taken care of for us by create-guten-block.

As long as we import our main block file into src/blocks.js (as we did above) then we don’t need to do any additional work. All JSX, ES6+, and Sass code will automatically be compiled into the following files:

  • dist/blocks.style.build.css: styles for editor and front end
  • dist/blocks.build.js: JavaScript for editor only
  • dist/blocks.editor.build.css: styles for editor only

These files contain the JavaScript and CSS for all blocks, so only one set of files needs to be enqueued, regardless of the number of blocks created!

We’re now ready to add a bit of interactivity to our block, and we can do this by first adding an attribute to store the image category.

This creates an attribute called category, which stores a string with a default value of 'nature'. We didn’t specify a location in the markup to store and retrieve the attribute value, so special HTML comments will be used instead. This is the default behavior if you omit an attribute source.

We need some way of changing the image category, which we can do via a select drop-down control. Update the edit function to the following:

Here is what it will look like:

Adding a block select drop down control

This is quite different from the previous static edit function, so let’s run through the changes.

First we’ve added a select drop-down control with several choices matching the image categories available on the PlaceIMG site.

PlaceIMG image categories

When the drop-down value changes, the setCategory function is called, which finds the currently selected category and then in turn calls the setAttributes function. This is a core Gutenberg function and updates an attribute value correctly. It’s recommended that you only update an attribute using this function.

Now, whenever a new category is selected, the attribute value updates and is passed back into the edit function, which updates the output message.

Image category updated

We have to complete one last step to get the random image to display. We need to create a simple component that will take in the current category and output an <img> tag with a random image obtained from the PlaceIMG site.

The request we need to make to PlaceIMG is of the form: https://placeimg.com/[width]/[height]/[category]

We’ll keep the width and height fixed for now, so we only have to add the current category onto the end of the request URL. For example, if the category was 'nature' then the full request URL would be: https://placeimg.com/320/220/nature.

Add a RandomImage component above registerBlockType():

To use it, just add it inside the edit function and remove the static output message. While we’re at it, do the same for the save function.

The full index.js file should now look like this:

Finally (for now), add the following styles to editor.scss to add a colored border around the image.

You’ll also need some styles in style.css.

Whenever the page is refreshed in the editor or on the front end, a new random image will be displayed. 

Finished editor view
Final front end view

If you’re seeing the same image displayed over and over, you can do a hard refresh to prevent the image being served from your browser cache.

Conclusion

In this tutorial we’ve covered quite a lot of ground. If you’ve made it all the way through then give yourself a well-deserved pat on the back! Gutenberg block development can be a lot of fun, but it’s definitely challenging to grasp every concept on first exposure.

Along the way, we’ve learned how to enqueue block scripts and styles and covered the registerBlockType() function in depth.

We followed this up by putting theory into practice and creating a custom block from scratch to display a random image from a specific category using the PlaceIMG web service.

In the next and last part of this tutorial series, we’ll add more features to our random image block via the settings panel in the block inspector.

If you’ve been following along with this tutorial and just want to experiment with the code without typing everything in, you’ll be able to download the final my-custom-block plugin in the next tutorial.

from Envato Tuts+ Code – WordPress https://ift.tt/2IVVh11

What Are the WordPress PHP Coding Standards?

What are the WordPress PHP coding standards? In this video from my course, Learn PHP for WordPress, you’ll learn all about the coding standards and why they’re important.

The WordPress PHP Coding Standards

//fast.wistia.com/assets/external/E-v1.js

 

What Are the WordPress PHP Coding Standards?

You can find the full WordPress PHP coding standards in the official WordPress handbook.

WordPress PHP coding standards

They’re essentially a set of best practices on how to use PHP in WordPress. We’ll go through some examples of what that means in practice in the rest of this tutorial.

As you can see, there are standards not only for PHP but also for accessibility and for the other languages that you’d use within WordPress. 

Why Are the PHP Coding Standards Important?

Why is it important that we all adhere to these standards? 

Well, there are two reasons. One of them is about quality of code, and the other is about consistency. 

So firstly, quality is important because it means that everybody coding in WordPress is creating code that will work, that will do its job, and that will be written in an up-to-date and high-quality fashion.

The second, which is about consistency, is equally important. It’s very likely that you’re going to be working with other people’s code from time to time. For example, if you’re creating a child theme, you might have to copy some of the code from the parent theme. And if you’re creating a plugin, that plugin could be a fork of an existing third-party plugin that you’re copying and adding extra functionality to. It’s really important that the way you code is consistent with the way that everybody else who codes PHP for WordPress writes code themselves. 

Examples of PHP Coding Standards for WordPress

So let’s take a look at some of the PHP coding standards. And I’m going to show you examples of these in some of the files in my theme.

Naming Conventions and Cases

Let’s start with naming conventions and cases. When you’re thinking about naming conventions, there are four things to think about:

  1. the functions within your theme or your plugin
  2. the files and the way that you name those
  3. any classes that you write
  4. any variables that you create

So let’s start with functions. Here’s the functions.php file in my theme as an example. 

the functionsphp file in my theme

You can see that I’ve got a function that I’ve defined called rachelmcc_register_widgets. That’s all written in lower case, and I’m using underscores between the words, which is how you should always write a function in WordPress.

As you’ll also see, I’ve used a prefix. That’s to ensure that this function doesn’t clash with any other functions that might be provided by my theme or by another plugin. So if I wrote a function that was just called register_widgets and one of my plugins also had a function called register_widgets, the two of them could clash. You might find that one of them overrides the other or that the plugin doesn’t work. 

So instead, I’m using a unique function that’s relevant to my theme. My theme is called rachelmccollin, so my functions have rachelmcc as a prefix. And it’s also important to use underscores for your functions and not to use hyphens.

You do use hyphens in two places. Firstly, you use hyphens when you’re defining CSS classes. So you can see that within my widgets, I’m defining CSS classes for my h3 element and also for the id of that widget area. And here, you use hyphens.

The other place that you use hyphens is in your file names. So this is front-page.php. 

the front-pagephp file

You should always use hyphens in your file names within your themes and your plugins; don’t use underscores. So here there is a call using locate_template. And loop-frontpage.php is a file, a template part that I’m calling, and you can see that that’s got a hyphen and not an underscore. 

On the other hand, my post type ID, which is a custom post type I’ve registered, uses an underscore: rmcc_blurb

Now you also might need to think about variables within your theme. Let’s look at loop-frontpage.php:

loop-frontpagephp file

Within this particular file, which is the one I was calling from that previous file, I’ve defined some variables, one called count and one called title. And you can see that I’m using lower case for both of those. 

The other place where you need to think about underscores and capitalization is when you’re using a class. Let’s go back to front-page.php:

the  front-pagephp file

And you can see here, I’m using the WP_Query class. So a class has a capital letter after the underscore, as well as at the beginning. So that’s where you use capitalization when you’re defining a class. It helps people working with your code instantly identify that it’s a class and not a function.

Using Single and Double Quotes

Now let’s have a look at how you would use single and double quotes in PHP for WordPress. 

You can use either single quotes or double quotes, depending on which works best for the specific code that you’re working with.

The reason that double quotes can sometimes be more helpful is that they make it easier to work with special characters. Here’s an example:

how to use single and double quotes in WordPress

Say you were writing a search template file, search.php. And within that, if nothing was found, you would put a paragraph that says, „I’m sorry, your search didn’t find anything. Why don’t you try again?“

I’ve put that within double quotes because the text contains apostrophes. Let me show you how that would work if we did it in single quotes. 

Example of single and double quotes

You need to put a backslash before the apostrophes in order for them to be output correctly within the HTML—otherwise, it’ll give you errors. Now I don’t know about you, but I’d rather just type it normally within double quotes than do all this within single quotes.

The other thing you need to remember is that if you need to put quotes within quotes, you either put single quotes within double quotes, or vice versa. It doesn’t matter which way around, but you can’t put single quotes within single quotes or double quotes within double quotes.

So here’s an example going back to my functions.php file. 

Example of single and double quotes in PHP

Within here I’ve got single quotes for the value of before_widget, and then within that, I’ve got double quotes for the ID and the class of that. I couldn’t use double quotes here and then put double quotes inside it, so that’s why I’m using single quotes there, because it’s better to use double quotes with your CSS. 

Indentation

Now, let’s look at indentation. And let’s continue looking at the functions.php file, which is quite a good example because I’ve indented a number of lines of code within it. 

You can see that the function name is on the left, and then within that the register_sidebar function is indented at one level. And the contents of that are indented again. 

So each time you’re putting content within braces or curly braces, everything inside that should be indented. And also for indentation, you should use line breaks. 

So let’s take a look at another file where there are single lines as well as double lines. 

Line breaks with a block of PHP

So here you can see I’ve got an if statement that’s got two lines of code within it. So I’ve put a line break above and below those two lines of code.

If there was only one line of code within that, I wouldn’t have to put those line spaces in—I would just put that straight inside my braces. 

Using spacing like this helps make it clear where your blocks of code are. And you can see also that indentation has been used. So there are multiple layers of indentation. 

The other thing you need to bear in mind is where you open and close your PHP tag and whether that is on the same line as your code or a different line. And that also depends on whether you’re coding a block of code or a single line.

Where you’ve got a block of code, you put your opening tag on one line and your closing tag on another line. That helps to make it obvious that it’s a block of PHP and that everything within those tags is PHP.

The other thing you have to make sure you do is use a full opening PHP tag. So don’t just use a question mark, as you might have done in some other systems that use PHP, because in WordPress you have to use the full PHP tag. 

If I wrote some PHP that was just on one line, I would put the PHP opening and closing tags on the same line.

PHP opening and closing tags on the same line

You can see that we’ve got some PHP that’s all in one line, and then after that I’ve got HTML. So the opening and closing tags go on the same line as my code. 

Conclusion

That’s an introduction to some of the elements of the WordPress PHP coding standards, and I’ve shown you some examples of them in my files and changed some as I’ve gone along to show you how things are done correctly. 

If you want to know more about the coding standards, there’s documentation on the WordPress website. And you can also check out this Envato Tuts+ series, which goes into all of the elements of the coding standards in detail.

Watch the Full Course

In the full course, Learn PHP for WordPress, you’ll learn all about PHP, the programming language that WordPress is built in.  

I’ll give you an overview of what PHP is and how it’s used for WordPress themes and plugins, with examples. You’ll go on to learn how to create a PHP file and use it to output HTML. Then you’ll learn to use functions, loops and if statements for coding custom WordPress themes and plugins.

You can take this course straight away with a subscription to Envato Elements. For a single low monthly fee, you get access not only to this course, but also to our growing library of over 1,000 video courses and industry-leading eBooks on Envato Tuts+. 

Plus you now get unlimited downloads from the huge Envato Elements library of 580,000+ creative assets. Create with unique fonts, photos, graphics and templates, and deliver better projects faster.

from Envato Tuts+ Code – WordPress https://ift.tt/2LmTlgd

How to Prepare Your Site for WordPress Gutenberg

Gutenberg is coming to WordPress soon. Is your website ready? While we still don’t know exactly what form it will take, this new content system will be added to WordPress core in the future. Let’s take a look at the potential impacts this could have on your site, and ways that you can determine, and fix, problem areas ahead of time.

What Is Gutenberg?

Gutenberg is a WordPress project that aims to give users more flexibility in the design of their content. Essentially, the project aims to replace the current editor, which performs mostly as a word processor, with a more visual and structured interface. Currently, Gutenberg is a plugin, and it grants users the ability to modify their content similarly to how Visual Composer or other drag-and-drop editors do—albeit in a simplified and highly intuitive way.

If you would like to  learn more about what Gutenberg is specifically, take a look at my earlier post „What Is WordPress Gutenberg?

The Pieces of Your Site

Gutenberg is a massive undertaking and will likely touch a large number of endpoints within your website. These are the three areas we’ll be scouring for issues:

  • Your Theme: Gutenberg comes with its own set of styles for content. Is your theme compatible? What will it look like with Gutenberg active?

  • Your Plugins: It’s possible that Gutenberg might interact with your other plugins in unexpected ways. We’ll look at what those might be, and what to do about any issues that arise.

  • Your Content: Gutenberg will affect how your content itself is displayed. We’ll examine how that might change what your pages look like, and go over some potential fixes if you’re having problems.

Setting Up a Testing Area

Before we get started, it’s a good idea to set up a testing area where you can experiment with Gutenberg without breaking your live site. Ideally, you should set up your own testing area or create a local copy of your site. For more on how to perform either of those tasks, see the following tutorial:

If neither of these is possible, you can do the testing directly on your site. Note that this can be risky, however, as we’ll be activating and deactivating a number of pieces of your site. If you are doing the testing live, please make sure to create a backup of your site before beginning.

Once you know where you’ll be testing, head to the plugins directory and find Gutenberg. Once it’s installed and activated, read on.

Put Your Theme Through Its Paces

Now that you have Gutenberg installed, let’s take a look at the first section of your site that might be affected: its theme. If there are already major problems at this point, such as database errors or problems with the WordPress admin, skip down to the What to Do When There Are Too Many Issues section.

Since Gutenberg interacts mainly with the content of the site, we only need to test a narrow set of things—luckily for us.

The first is that Gutenberg comes with its own style sheet and set of styles. Check each of the different page types and templates used on your site to make sure that they still appear appropriately. The main focus here is going to be elements within the main content area of your pages—especially content and image blocks. If you see any issues, it’s likely that Gutenberg’s styles are taking precedence over your site’s.

To correct this, you’ll need to identify where the problem is coming from. Typically, it will be a CSS selector focused on an HTML element, or it could be a priority of Gutenberg styles over your own classes. Whatever the case may be, try to identify where the error is occurring. Next, determine why the Gutenberg styles are overriding yours, and correct your code to allow it to take precedence.

Try to make any corrections within your own theme (or better yet, in a child theme or specified area for CSS in your theme), rather than altering Gutenberg. If you alter any of the files in Gutenberg directly, it’s likely to be overwritten when the plugin is updated.

In a similar fashion, you’ll want to give your admin area a once-over for any styling issues. Theme options and other custom-implemented sections generated by your theme appear to be the biggest culprits so far. Once you’ve identified styling issues in these areas, you can typically correct them by changing or creating a child theme and adjusting the CSS there.

Do Your Plugins Work?

After your theme is squared away, next up are your site’s plugins. Specifically, keep an eye on any plugins that provide shortcodes that you use in your content (e.g. Gravity Forms), plugins that affect the appearance of your content (e.g. accessibility plugins that affect text size), and plugins that directly insert elements into your page (such as Advanced Custom Fields).

Looking at Shortcodes

To audit this area, first gather a list of any shortcodes that you may be using, along with what pages they exist on. With your list in hand, visit each of these pages to see if they are performing as intended. If you encounter any styling issues, then it’s likely that you’re experiencing the same problem as above and need to readjust your styles.

However, if you’re getting the dreaded rendered shortcode—that is to say that your page is displaying the [shortcode] instead of doing what it should—there is another solution. In this case, you can look at the block where the shortcode is and confirm that it’s not considered text (looking for and removing unwanted tags around the shortcode). If the problem still persists, moving the shortcode to a more appropriate block type should get everything back up and running.

Content Appearance

This issue arises from the same problem we’ve covered previously: style overrides. Identify the elements that are being affected and correct the CSS.

Element Creation

The final area that we’ll be looking at for conflicting issues concerns element creation.  Any plugin that inserts HTML elements into a page without using shortcodes is suspect here—for example, when PHP pulls in custom fields from the Advanced Custom Fields plugin.

The most common slip-up with element creation revolves around blocks being mismatched. Since Gutenberg provides its own styles, there is a chance that if your elements are created inside an unintended block, they may render incorrectly. The fix for this is making sure your code adds elements to the block where you want them to be.

Is Your Content Appearing as Necessary?

This is not quite as urgent as the other problems we’ve discussed, but there might be some complications with how your content is rendered. Most of these problems will be from minor styling changes or how blocks are organized. To correct this, you’ll have to play around with the block system until you get your page how you want it.

What to Do When There Are Too Many Issues

Did you run into a problem that you couldn’t solve with the suggestions in this article? Don’t panic! There’s still some time before Gutenberg hits WordPress Core.

First, record what the error is and what steps led to the error. The more information that you can gather, the better. Pass all of this information along to the Gutenberg team. With luck, they’ll be able to determine the issue and fix it in a future release.

If you were working on a staging site, then at this point, that’s all you can do for now. Continue to check the release notes to see if your problem is solved, or possibly work on solving it yourself.

If you were working on your live site, deactivating Gutenberg should put everything back to normal. If not, then now is the time to revert to that backup you made!

Good Luck on Your Install!

Gutenberg aims to be a massive change to the WordPress environment, one that looks to change content for the better. Before it hits the main branch, make sure to check that your site will function with the new changes. If you have problems other than what’s listed here, better solutions, or corrections for anything in this article, please leave a comment below!

from Envato Tuts+ Code – WordPress https://ift.tt/2ISGKCW

How to Create a Custom Settings Panel in WooCommerce

Final product image
What You’ll Be Creating

WooCommerce is by far the leading ecommerce plugin for WordPress. At the time of writing, it has over 3 million active installations and is reportedly behind over 40% of all online stores.

One of the reasons for WooCommerce’s popularity is its extendability. Like WordPress itself, WooCommerce is packed full of actions and filters that developers can hook into if they want to extend WooCommerce’s default functionality.

A great example of this is the ability to create a custom data panel.

What’s Covered in This Tutorial?

This tutorial is split into two parts. In part one, we’re going to be looking at:

  • adding a custom panel to WooCommerce
  • adding custom fields to the panel
  • sanitizing and saving custom field values

Then in part two, we’ll look at:

  • displaying custom fields on the product page
  • changing the product price depending on the value of custom fields
  • displaying custom field values in the cart and order

What Is a WooCommerce Custom Data Panel?

When you create a new product in WooCommerce, you enter most of the critical product information, like price and inventory, in the Product data section.

WooCommerce custom data panel

In the screenshot above, you can see that the Product data section is divided into panels: the tabs down the left, e.g. General, Inventory, etc., each open different panels in the main view on the right.

In this tutorial, we’re going to look at creating a custom panel for product data and adding some custom fields to it. Then we’ll look at using those custom fields on the front end and saving their values to customer orders.

In our example scenario, we’re going to add a ‚Giftwrap‘ panel which contains some custom fields:

  • a checkbox to include a giftwrapping option for the product on the product page
  • a checkbox to enable an input field where a customer can enter a message on the product page
  • an input field to add a price for the giftwrapping option; the price will be added to the product price in the cart

In the back end, it’s going to look like this:

Giftwrap panel

And on the front end, it will look something like this:

Front end example

Create a New Plugin

Because we’re extending functionality, we’re going to create a plugin rather than adding our code to a theme. That means that our users will be able to retain this extra functionality even if they switch their site’s theme. Creating a plugin is out of scope for this tutorial, but if you need some help, take a look at this Tuts+ Coffee Break Course on creating your first plugin: 

Our plugin is going to consist of two classes: one to handle stuff in the admin, and one to handle everything on the front end. Our plugin file structure is going to look like this:

Project structure

Admin Class

First up, we need to create our class to handle everything on the back end. In a folder called classes, create a new file called class-tpwcp-admin.php.

This class will handle the following:

  • Create the custom tab (the tab is the clickable element down the left of the Product data section).
  • Add the custom fields to the custom panel (the panel is the element that’s displayed when you click a tab).
  • Decide the product types where the panel will be enabled.
  • Sanitize and save the custom field values.

Paste the following code into that new file. We’ll walk through it step by step afterwards.

Create the Custom Tab

To create the custom tab, we hook into the woocommerce_product_data_tabs filter using our create_giftwrap_tab function. This passes the WooCommerce $tabs object in, which we then modify using the following parameters:

  • label: use this to define the name of your tab.
  • target: this is used to create an anchor link so needs to be unique.
  • class: an array of classes that will be applied to your panel.
  • priority: define where you want your tab to appear.

Product Types

At this stage, it’s worth considering what product types we’d like our panel to be enabled for. By default, there are four WooCommerce product types: simple, variable, grouped, and affiliate. Let’s say for our example scenario, we only want our Giftwrap panel to be enabled for simple and variable product types.

To achieve this, we add the show_if_simple and show_if_variable classes to the class parameter above. If we didn’t want to enable the panel for variable product types, we’d just omit the show_if_variable class.

Add Custom Fields

The next hook we use is woocommerce_product_data_panels. This action allows us to output our own markup for the Giftwrap panel. In our class, the function display_giftwrap_fields creates a couple of div wrappers, inside which we use some WooCommerce functions to create custom fields. 

Note how the id attribute for our outer div, giftwrap_panel, matches the value we passed into the target parameter of our giftwrap tab above. This is how WooCommerce will know to display this panel when we click the Giftwrap tab.

WooCommerce Custom Field Functions

In our example, the two functions we’re using to create our fields are:

  • woocommerce_wp_checkbox
  • woocommerce_wp_text_input

These functions are provided by WooCommerce specifically for the purpose of creating custom fields. They take an array of arguments, including:

  • id: this is the ID of your field. It needs to be unique, and we’ll be referencing it later in our code.
  • label: this is the label as it will appear to the user.
  • desc_tip: this is the optional tool tip that appears when the user hovers over the question mark icon next to the label.

Note also that the woocommerce_wp_text_input function also takes a type argument, where you can specify number for a number input field, or text for a text input field. Our field will be used to input a price, so we specify it as number.

Save the Custom Fields

The final part of our admin class uses the woocommerce_process_product_meta action to save our custom field values.

In order to standardize and optimize how it stores and retrieves data, WooCommerce 3.0 adopted a CRUD (Create, Read, Update, Delete) method for setting and getting product data. You can find out more about the thinking behind this in the WooCommerce 3.0 announcement.

With this in mind, instead of the more familiar get_post_meta and update_post_meta methods that we might have used in the past, we now use the $post_id to create a WooCommerce $product object, and then apply the update_meta_data method to save data. For example:

Please note also that we’re careful to sanitize our data before saving it to the database. There’s more information on sanitizing data here: 

Main Plugin File

When you’ve created your readme.txt file and your main plugin file tutsplus-woocommerce-panel.php, you can add this code to your main file.

This will initiate your admin class.

When you activate your plugin on a site (along with WooCommerce) and then go to create a new product, you’ll see your new Giftwrap panel available, along with custom fields. You can update the fields and save them… But you won’t see anything on the front end yet.

Conclusion

Let’s just recap what we’ve looked at so far in this article.

We’ve looked at an example scenario for adding a custom ‚Giftwrap‘ panel to WooCommerce. We’ve created a plugin and added a class to create the panel. Within the class, we’ve also used WooCommerce functions to add custom fields, and then we’ve sanitized and saved those field values.

from Envato Tuts+ Code – WordPress https://ift.tt/2KgZBEL

WordPress Gutenberg Block API: Block Look and Feel

The new WordPress editor (codenamed Gutenberg) is due for release in version 5.0. Now is the perfect time to get to grips with it before it lands in WordPress core. In this series, I’ll show you how to work with the Block API and create your very own content blocks which you can use to build out your posts and pages.

In the first post of this series, we had an overview of the Block API and created a simple block for testing. We’ll be taking a closer look at the Block API shortly, but first let’s edit the default block we created in the previous post to get a feel for how easy it is to make changes to an existing block.

If you remember, our custom block rendered differently on the front and back end to demonstrate that you have complete control over how the block is rendered inside the editor and how site visitors see the block.

Default views for our custom block

If you’ve been following along then open up the /wp-content/plugins/my-custom-block/src/block folder where the block source code is located. That folder contains a JavaScript file and two Sass files, which control the block’s behavior and how it renders inside the editor and on the front end.

Block source code files

The block.js JavaScript file contains JSX, which is transpiled during the build process into valid JavaScript. Similarly, the two Sass files are converted to standard CSS.

During the build process, these files require processing to create the distribution files inside the plugin’s dist/ folder. These are the actual files enqueued by WordPress as they contain valid JavaScript and CSS that all browsers can understand.

Fortunately, the create-guten-block toolkit handles building and transpiling for us by watching for changes to our block files. This is a really nice feature as it’s one less thing for us to worry about. We can just focus on writing our block code (and styles), and the plugin files will all update automatically. Nice!

Just make sure you run the npm start command from inside the plugin root folder to trigger file watching.

Time to Edit Some Code!

Don’t worry about the details of the JSX code in block.js just yet as we’ll cover that in detail later on. For now, let’s just focus on making some simple changes to the block output for the front and back end views.

Open up block.js, find the edit method for the object that’s the second argument passed to registerBlockType(), and replace it with the following:

This method controls how the block renders in the editor window. Now find the save method and replace it with:

This method is used to render the block output on the front end.

In style.scss, replace all styles with:

Then, in editor.scss, replace all styles with:

You can see in the screenshots below how these changes affect the rendering of our block depending on whether we’re viewing it in the editor window or the front end.

Updated editor view
Updated frontend view

We won’t cover enqueueing block scripts just yet, but it’s enough for now to know that editor.scss styles are only applied to the editor window and style.scss is added to both the editor window and the front end. Therefore, styles that are used both in the editor and front end can be omitted from style.scss.

Notice how in the Sass files we reference a lengthy CSS selector to target our block elements.

This class is automatically added by Gutenberg to the block container element on the front end, but we have to apply it manually in the editor window to get the same class, as you can see in the edit method below.

The class name generated by Gutenberg is determined as follows: wp-block-[block namespace]-[block name.

In our case, we used the create-guten-block toolkit to create our block, which uses cgb for the namespace by default, and block-my-custom-block is based on the block name we specified. This results in the CSS class name wp-block-cgb-block-my-custom-block being added to the block container. The namespace and block name are used by Gutenberg internally to uniquely identify blocks.

When making changes to block files there, I found a couple of pain points worth mentioning.

Firstly, when making changes to the edit method, I found myself having to clear the browser cache before refreshing the editor window in order to see the latest changes. This didn’t happen all of the time, but it was quite often the case. If you find the same thing happening to you, just clear your browser cache and try again.

Secondly, when editing the contents of the save method, something strange seems to happen to the editor window when it’s next refreshed.

To demonstrate this, I added a new list item (<li>Indigo</li>) in the save method and then refreshed the post editor (after having to clear the cache again, of course!). Here’s the result:

Block update issue

If you choose either Convert to Blocks or Edit as HTML then you get presented with the contents of the save method, which is meant to be viewed on the front end and not in the editor.

Convert to blocks and edit as HTML views

This is very confusing, and the only obvious way to bring things back to normality was to delete the block from the editor window and reinsert it again. As I mentioned in the previous post, Gutenberg is still a work in progress, and this is a good example of that!

Hopefully this will be made more intuitive in future versions, but for now it’s just something to watch out for. When making changes to the save function, be prepared to delete the related blocks in the editor window and add them again.

As mentioned previously, the output from the save and edit methods can be completely different. However, in most cases you’ll probably want the front end output to match the editor output so that the editing experience is as consistent as possible with front-end rendering.

In our contrived example above, I only added different content and styles in the editor and front-end view for demonstration purposes.

Block API Overview

The Block API is made up of a set of JavaScript objects added to the global wp admin object. And because wp is global, we don’t need to specifically import it in our source code—it’s available on demand.

The objects available in wp depend on the admin page you’re currently viewing. For instance, if you’re customizing your site then wp includes the main customizer API object. 

Currently, however, the Gutenberg Block API is only available on the post editor. I anticipate this will change in the future when integration between the post editor and site customizer moves closer.

You can view the structure of wp by opening up the Gutenberg editor and entering wp in the browser console.

Block API objects added to global wp JavaScript object

As you can see, wp contains many objects, but the ones we’re most interested in are:

These objects give you access to all the tools needed to create some very complex blocks. Try typing their full object names in the browser console to explore these objects further.

For example, if you type in wp.blocks and expand the object, you’ll see one of the available functions is registerBlockType(). This is a very important function which we’ll cover in depth in the next post

The wp.elements Object

This object is the abstraction layer on top of React (and ReactDom) which exposes React functionality in a predictable and consistent manner. This remains true even if the underlying implementation is altered or changed completely.

So long as the interface stays the same, plugins that interact with the Block API won’t be affected in the future.

The wp.blocks Object

The core function to create a block (registerBlockType()) is contained in wp.blocks along with other functions necessary for general block management such as:

  • getBlockType()
  • getBlockContent()
  • getBlockAttributes()
  • hasBlockSupport()
  • isValidBlock()

This object also contains a set of reusable blocks that you can include in your own blocks to provide functionality with no additional overheads. These out-of-the-box ready blocks can speed up block development dramatically, and we’ll be making use of some of them in the next post as we delve further into block creation.

Some of the available ones are:

  • alignment toolbar
  • autocomplete
  • media uploader
  • color palette
  • rich text editor

The wp.components Object

The wp.components object also contains reusable components, but these are more generic and are typically used to create additional UI elements in the editor window, such as control panels for block settings.

These include:

  • button
  • checkbox
  • code editor
  • dash Icon
  • date/time
  • dropdown
  • menu item
  • radio button
  • range control

The wp.data Object

The data module manages application state in the Gutenberg editor, which includes storing settings for each block. We’ll be taking a look at different ways you can add settings to a block in the final post of this series.

wp.data is implemented on top of Redux, so when Gutenberg is merged with core, we won’t just have access to React but also to a complete centralized data store powered by Redux! 

The wp.i18n Object

Plugins and themes have been able to easily translate PHP strings for years now, and a similar method is also available for translating strings in JavaScript thanks to the wp.i18n object. This means all strings contained in your block—including the block name, keywords, and labels—can be translated into any language.

If you’ve used the standard PHP translation functions before then you’ll feel right at home as the process is pretty much the same. I think this is a smart move as it will encourage developers to enable string translations in their blocks from the outset.

Inside your block code, translating a string is as simple as:

Conclusion

In this tutorial, we’ve implemented a basic block and edited the code. We’ve also seen that we have total control over block rendering and can have different block views in the editor compared to the front end.

The editor still has some issues which can take you by surprise from time to time—this serves as a reminder that Gutenberg is still in development and may not be ready for use on production sites.

Finally, we finished off with an overview of the block API, which introduces several new objects on the global wp JavaScript object to create and manage blocks.

In the next post, we’ll pick up the pace and create a more comprehensive block. To do so, we’ll explore the registerBlockType() function in depth. We’ll also take a closer look at properly enqueueing your block scripts.

from Envato Tuts+ Code – WordPress https://ift.tt/2I92wyI