Creating a New Plugin
Introduction
We are going to begin creating a new plugin. A long time ago I promised we would develop a block with WordPress as recommended structure for a block. WordPress strongly advocates for one block per plugin. The plugin we’ve been developing breaks this practice, which is perfectly fine. It’s not uncommon for plugins to add multiple blocks to a site for demonstration purposes. I want to show you how to develop a single block for a plugin. After we’re finished developing a block, we will submit this plugin to the official WordPress repository. The WordPress community will be able to freely install our block onto their site. It will be a lot of fun. So let’s get started.
Creating a New Plugin
Our first step is to create a new plugin. Let’s try using the Create BLOCK package to help us create a new plugin for block development. In your editor, open the command line. Let’s write the following command now: npx @wordpress/create-block alert-box --namespace=you-plus
. This command is mostly familiar to us. We’re constructing NPM to temporarily install and execute the create block package. This package will scaffold a plugin for us. The name of the plugin will be called Alert Box. I’m introducing a new option called namespace. The namespace option will configure the namespace for our block. This plugin will occupy the same namespace as our original plugin. Let’s run this command. After a few seconds, a new directory has been created called Alert Box.
Adjusting the New Plugin
Let’s make some adjustments to the new plugin. First, let’s start with the main plugin file. The package will generate a file header. Most of these values are fine except for the description and author. Let’s set the description to the following: “Add an alert box to output important information to the reader.” Next, let’s set the author field to our name. Everything else in this file is fine. Let’s take a moment to explore this file. At the bottom of the file, a function called ue_plus_alert_box
will register a block. This function is executed during the init hook. Overall, we have a simple plugin file.
Updating the Package File
Before moving on to the script files, let’s update the package file. In this file, we are going to update the description and author fields. The values for these fields will have the same values as the fields from the file header in the main plugin file. Let’s copy them over to this file. Great. This step is optional. However, we are going to publish this plugin to the official WordPress plugin repository. These details matter as much as the code for the block. Otherwise, our plugin may get rejected.
Preparing Other Files
We can move on to preparing the other files in the resource section of this lecture. I provide a link to a list of starter files. I want you to update the respective files with the code from this gist. In total, there are four files. You can find them in the source directory of our project. Pause the video and good luck.
Reviewing the Files
Welcome back. Hopefully, you are able to update the files in our project. The code for the block can be found in the source directory. WordPress will outsource the edit and save functions into separate files. The functions from each file are imported into the index file. This file contains the block registration. Let’s go through the files together.
Block File
Starting with the block file. We have a typical configuration file for our block. This block has four attributes for storing the content of the block: an icon, background color, and text color.
Edit JS File
Next, let’s move on to the edit JS file. Inside this file, I removed most of the comments from the original edit file. The comments contain information on the various components and functions imported into the file. They’re great for beginners; however, they are not necessary. It’s up to you if you would like to keep them around. The most notable piece of code in this file is inside the inspector controls component. Inside this component, we’re using the panel color settings block to add color options to the block. While this component is not new to us, it’s been a while since we’ve added this component to our blocks. This component provides a UI for modifying multiple colors. In this example, the component will modify the BG color and text color attributes. Other than that, there’s nothing else worth saying about this block. It’s a very simple block. The block will render content with an icon.
Saved JS File
Let’s move on to the saved JS file. This file is very similar to the edit JS file but without the sidebar content.
Style File
The last file is called style. Since we haven’t had the opportunity to talk about Sass, in the next lecture, we’ll dive into this file. For now, let’s try building the block behind the scenes.
Building the Block
The Create BLOCK package will prepare the WP Scripts package for our plugin. We can skip the step of adding this package before running the command. Our editors are not pointed to the plugin. I’m going to quickly point my editor to the Alert Box plugin. After making those changes, we can build the project. The command is the same as before: run the npm run start
command. The command line will produce a successful result.
Activating the Plugin
One last thing: let’s activate the plugin from the admin dashboard in the browser. Navigate to the plugins page. Next, activate the alert box plugin. The plugin will activate without throwing an error. Perfect.
Exploring SAS
Introduction
We are going to explore a language called SAS. In the resource section of this lecture, I provide a link to the official site for SAS. SAS is a programming language for CSIS, which might sound strange. CSIS is one of the simplest languages you can learn. There’s not much to it. On the other hand, it’s not a powerful language. SAS aims to solve CSIS issues by adding features found in programming languages.
Features of SAS
SAS supports functions, loops, directives, inheritance, etc. For this course, we decided not to use SAS. In my opinion, I prefer another tool called Post CSIS. However, you’re likely to find SAS and other plugins for this reason. Let’s try learning SAS.
Installation and Usage
Typically, the first step is to install SAS. Browsers do not support SAS code written with SAS; it must be compiled in CSS. By using the Create Blocks package, we can skip this step altogether. The developers of this package have added native support for SAS with blocks. We can start writing SAS immediately in our editors.
Writing SAS
Let’s open the style SCC file. SAS files can be written inside files with the SAS or SCSS extension. The SCSS extension is more common. If you were to look through this files code base, you’re going to notice that SAS is very similar to CSS. You can think of SAS as a language that extends CSS. All CSS features are supported. The SAS syntax rules apply to SAS.
Nested Selectors
Let’s look at one of the most common features available inside the WP block u-plus-alert-box
class. We have a list of CSS properties. However, things don’t stop there. An additional selector has been added inside the curly brackets of the current selector. SAS supports nested selectors. The idea of nesting was inspired by HTML. We can add elements inside elements. Children elements would inherit properties from parent elements. The same idea applies to nested selectors in SAS.
Example of Nested Selectors
A nested selector is a shortcut for producing a long selector. For example, the first nested selector will produce the following selector: WP block u-plus-alert-box is-style-accented
. In the child selector, we have an ampersand character. This character represents the parent selector. SAS will convert this character into the parent selector during compilation, thus giving us the final selector. As you can see, it’s shorter to write this selector.
Another Selector Example
Let’s look at another example. Below this selector, the child selector does not have the ampersand character. By not including this character, a space will separate the parent and child selector. This example will produce the following selector: WP block u-plus-alert-box dash icon
. By using nested selectors, we can quickly create long selectors.
Benefits of Nested Selectors
In addition, this feature provides clarity on the relationship between selectors. Without nesting, it can be difficult to organize CSIS. It’s very clear that these properties will only be applied to these classes. This is just one feature of SAS. Since this is not a SAS course, I won’t be diving any deeper. However, feel free to continue learning about SAS after finishing this course. There are many developers who enjoy using this language.
Discussing the Ed Success File
Introduction
In this lecture, we are going to quickly discuss a file called Ed Success. You can find this file within the source directory. This file contains styles for the Gutenberg editor.
Role of the Ed Success File
The Scripts package will search for a file called Editor that asks if this file exists within our project. The compiled CSS file will not be bundled with the other files. The package will extract this file into a separate file in the build directory. A file with a similar name cannot be found behind the scenes. The builder has renamed the file to indexed CSS. If you look inside this file, you’ll find the same styles from the editor SKS file.
Purpose of the Ed Success File
It’s a simple feature for separating editor styles from the main styles of a block. There isn’t a reason to load styles for the editor on the front end. They take up an unnecessary amount of disk space. For this plugin, we do not need editor styles.
Removing the Ed Success File
Let’s remove this file from our project in the source directory. Delete the editor.scss
file.
Modifying the Block JSON File
Next, open the block.json file. Towards the bottom of the file, remove the editor style option. The editor’s style option will load a CSS file in the editor. The Scripts package will add this option for loading the indexed CSS file. Since we do not need editor styles, this option can be safely removed.
Finalizing Changes
The last step is to remove the import statement for this file from the edit.js file. Inside this file, remove the import statement. After making those changes, your project should be fully functional. You can check the command line for errors. If you spot errors, you may need to restart the npm run start
command. After restarting, the error should go away.
Exploring Additional Features for Blocks
Introduction
We are going to explore additional features that can be applied to our blocks. WordPress has dozens of blocks with similar features. For example, blocks can be aligned to take up the width of the page. It’s redundant to recode these features for each block to avoid repetitive code. WordPress has a list of features that can be applied to any block. This saves us the time of recreating these features for our block.
Resources
In the resource section of this lecture, I provide a link to the BLOCK Support Documentation page. We can enable features for our block by updating the block file. The various features are documented on this page. We won’t have a chance to go through every single feature. However, you’re more than welcome to explore them after finishing this section.
Features to Implement
There are two features we are going to look at.
Disabling HTML Modification
The first feature is disabling HTML from our block. Let’s look at an example in another tab. I have added the alert box block to the page on the toolbar. There’s an option for modifying the block with HTML by default. This option is available for all blocks. This feature can be dangerous. Users can easily break a block by modifying the HTML. This option can be disabled. Let’s disable this option for our block.
Supporting Wide Alignment
Another feature we will implement in our block is wide aligning. The block can take up the entire width of the page. This option is available from the toolbar. By default, it’s disabled. I think our block should support wide alignment. Let’s try supporting these features in your editor.
Updating the Block JSON File
Open the block.json file. At the bottom of the file, there’s an object called supports. Inside this object, we can add a list of features to enable. The HTML feature can be disabled by setting the HTML option to false. Next, let’s add an option called align with an initial value of true. By setting the align option to true, all alignment options will be enabled. This means a block can be aligned left, center, right, wide, and full.
Limiting Alignment Options
You may not be interested in supporting all alignment options. For example, we can limit the alignment to full by adding this option to the array. Our block can support all alignments. We don’t need to use an array, so I’m going to revert this option to the original value.
CSS Adjustments
There are more features we can enable, but let’s keep it simple. There’s one more thing I want to mention before we test our work. Open the style.css file. WordPress will add a class for the current alignment option. We can select this attribute with our CSS.
Applying CSS for Full Width
In the CSS, I’m selecting the element. If the full option is selected, if the block is fully aligned against the page, this option will be applied to our block. In this example, I’m removing the border radius from the block.
Testing the Block
Let’s check out the block by refreshing the page. Next, add the alert box block to the page. If we click on the toolbar, the option to edit the block with HTML is gone. In addition, the alignment options have been added to the block without doing anything else. These options are automatically available on our block. We do not need to manage these values.
Note on Alignment
Keep in mind that the alignment option will not work on the front end. The page has a sidebar which does not allow for full width.
Exploring Block Variations
Introduction
We are going to explore a useful feature for helping site builders: block variations.
Example of Block Variations
Let me show you an example. Currently, I’m viewing the Gutenberg editor. If I were to add a new block, there’s a category called Embed. You may scroll down the list of blocks to find this category. WordPress supports various platforms for embedding content into the page. At first glance, these may seem like different blocks. However, these blocks are variations of the embed block. It’s the same block, but with different names and icons. The behavior of the block is still the same. Variations were introduced to showcase the different appearances a block can have.
Adding a Variation
Let’s try adding a variation for our block. To get started, check out the resource section of this lecture for a link to a gist. For this demonstration, I will be providing different icons: one icon for the original version of the block and another icon for the variation. The variation will be called “accented.”
Creating the Icons File
Let’s copy this code to our clipboard. Next, head on over to your editor inside the source directory. Create a file called Icons.js
. Paste the code into this file.
Updating the Block File
Next, update the block file. The icon’s property can be removed from the file. We can start importing the icons into our block. In your editor, open the index.js
file. At the top of the file, import the icons file. Next, add the icon option to the object. Set the icon to the icons.default
property.
Defining Variations
After adding the icon, we can begin adding the variation. Variations can be defined by adding the variations
array to the configuration object. Inside this array, we can add objects for each variation of our block. For this example, let’s add one object.
Setting Variation Properties
Inside this object, we must provide a name for our variation. The name must be unique and cannot conflict with other block names. I prefer to use the original name with an additional word attached to it. For example, let’s set the name to the following: ue-plus/alert-box-accented
. The variation is called “accented.”
Next, let’s add a property called title
. This property will have the following value: Alert Box Accented
. The title will be presented on the front end to the user.
Afterward, let’s set the icon property to the icons.accented
property. The properties for the variation are exactly the same as the properties for a block file. The main difference is that we do not need to include the edit or save functions. The variation will inherit the functions from the parent configuration.
Customizing the Variation
The question is, how can we make our variation different? It’s common practice to modify the default values of the attributes. Let’s add an object called attributes
. Next, change the text color attribute to the following color: #111827
. Lastly, let’s change the name of the class by setting the class name to is-style-accented
.
Understanding Class Names
Technically, the class name attribute is not a valid attribute on our block. However, WordPress treats this value as an attribute. We can modify it through the attributes object. This is where the true power of variations comes in. If a variation is added to the page, WordPress will allow us to insert a class for completely changing the appearance of the block. It’s common practice to use the name is-style
, followed by the name of the variation.
Testing the Variation
I’ve already prepared styles for this class. You can refer to the style file for the styles. Let’s try testing our code in the browser. Refresh the page. Next, try searching for the alert box block. As you can see, the results will display two blocks. They are the same block, but with different classes.
Adding the Variation
We can click on the “Alert Box Accented” block to add it to the page. The block has an entirely different appearance than before. However, it’s still the same block. If you look at the sidebar, WordPress does not use the modified name. According to WordPress, we’re working with the alert box block.
Adding Block Styles for Variations
Introduction
We’ll explore how to add an option for toggling between different block styles. This will enhance the user experience, allowing for quick design changes without the hassle of deleting and recreating blocks.
The Problem
Currently, if I want to change the design of the alert box block after adding it to the page, I have two options:
- Remove the block and add the other variation.
- Manually write the name of the class in the class field.
Both of these options are not ideal. Removing and adding blocks wastes time, and forcing users to memorize class names is inconvenient.
The Solution: Block Styles
WordPress provides a solution with Block Styles, allowing users to switch between variations by toggling a class on the block. You can find more information about this feature in the resource section of this lecture.
Implementing Block Styles
Let’s apply block styles to the alert box:
- Open the
block.json
File:- In your editor, locate the
block.json
file for the alert box.
- In your editor, locate the
- Add the
styles
Array:- At the bottom of the configuration file, create an array called
styles
.
- At the bottom of the configuration file, create an array called
- Define Styles:
- Inside this array, we’ll add an object for each style we want to implement.
Adding the Default Style
- First Style Object:
- Add the following properties for the first style:jsonCopy code
{ "name": "regular", "label": "Regular" }
- This will be the default style of the block. There’s no need to define a specific class for this style, but it’s good to have an option to revert to the original style.
- Add the following properties for the first style:jsonCopy code
Adding the Accented Style
- Second Style Object:
- Add another object for the accented style:jsonCopy code
{ "name": "accented", "label": "Accented" }
- The name property is crucial because WordPress will prefix it with
is-style-
to create the class name (is-style-accented
).
- Add another object for the accented style:jsonCopy code
Optional Default Style
- If you want to set one of the styles as the default, you can add an optional property
isDefault
:jsonCopy code"isDefault": true
Testing the Block Styles
Now it’s time to test our implementation:
- Refresh the Page:
- Once you’ve saved your changes to the
block.json
file, refresh the page in the browser.
- Once you’ve saved your changes to the
- Select the Alert Box Block:
- Click on the alert box block in the sidebar. You should see a new panel for switching between styles.
- Toggle Styles:
- You can now easily toggle between the regular and accented styles without manually adding classes.
- Under the Advanced panel, you can monitor the class field for updates as you switch styles. You’ll notice that the class name changes automatically.
Understanding Deprivations and Validation in Blocks
Introduction
We’ll discuss the concept of deprivations in the context of block development. We’ll focus on the differences between dynamic and static blocks, and how changes to block templates can lead to validation issues in WordPress.
Dynamic vs. Static Blocks
- Dynamic Blocks: These blocks use server-side rendering, making them easier to maintain. When modifications are made, they are less likely to break the editor experience.
- Static Blocks: These blocks are rendered on the client side. If you make changes to a static block’s template without updating the corresponding functions, it can lead to issues, particularly in the editor.
Example of a Deprivation
Let’s illustrate a potential problem:
- Open the
block.json
File:- Locate the
attributes
section and change the content tag from a<p>
to a<div>
.
- Locate the
- Update the Edit and Save Functions:
- Open the
edit.js
file and update theRichText
component’stagName
property todiv
. - Similarly, in the
save.js
file, set thetagName
property todiv
.
- Open the
- Refresh the Page:
- After making these changes, if you refresh the page, the block may break.
The Validation Process
When a block is rendered:
- Attribute Extraction: WordPress retrieves attribute values from the database.
- Rendering: These values are passed to the current
save
function of the block. - Comparison: The output of the
save
function is compared to the original template saved in the database.
If these outputs do not match, WordPress identifies this as a validation failure. You’ll see an error message indicating that the block failed validation.
Why Validation Matters
Validation ensures:
- Consistency: Users experience consistent results, even after updates.
- Smooth Upgrades: If a block fails validation, users may see unexpected results, which can lead to confusion and a poor user experience.
Example of Validation Failure
When a block breaks:
- The template created by the
save
function (after modifications) might not contain the expected content or structure. - The original template saved in the database does not match the output, leading to validation failure.
Handling Block Upgrades with Deprivation
Introduction
In this lecture, we’ll focus on helping WordPress understand updates made to our blocks. We’ll discuss the concept of block deprecation and how to ensure a smooth upgrade path for users.
Understanding Block Deprecation
When we change a block’s template, WordPress can struggle to extract the existing content attributes from the database. To address this, WordPress offers two primary strategies for managing deprecated blocks:
- Creating a New Block: This involves starting fresh with a new block that incorporates the latest features.
- Updating the Current Block: This is the more user-friendly option, allowing us to maintain the existing block while providing a copy of the original template.
Creating a Deprecated Version
Let’s implement the second strategy by creating a deprecated version of our block.
Step 1: Create a New File
- File Creation: In your editor, create a new file named
v1.js
. This will store the configuration for the original version of our block.
Step 2: Define the Deprecated Block
- Basic Configuration:
- Import an empty object in the default namespace.
- Define the necessary configuration details, focusing on three key properties.
Step 3: Specify Supported Features
- Supported Features:
- Import the original block file and use the spread operator to include its supported features.
import { supports as originalSupports } from './block'; const deprecatedConfig = { supports: { ...originalSupports }, // other properties... };
Step 4: Define Attributes
- Attributes:
- Spread the attributes from the latest block version into your deprecated block.
- Override the content attribute to reflect the original configuration.
attributes: { content: { type: 'string', source: 'html', selector: '.alert-box-content p', }, },
Step 5: Implement the Save Function
- Save Function:
- This is critical as it must produce the same template that was saved in the database.
- Copy the original save function from the latest version and modify the tag name to
p
.
export const save = (props) => { return ( <RichText.Content tagName="p" value={props.attributes.content} /> ); };
Step 6: Register the Deprecated Block
- Registration:
- Open your
index.js
file. - Import the
v1.js
file. - Add the deprecated configuration to the block registration object.
deprecation: [v1],
- Open your
Testing the Implementation
Step 7: Refresh and Validate
- After implementing the above steps, refresh your browser.
- You should no longer see validation errors; instead, WordPress will run the save function from the deprecated version.
- The block’s content should now display correctly.
Publishing a Plugin to the WordPress Repository
Introduction
I’ll guide you through the process of publishing a plugin to the WordPress repository. While the process is straightforward, be aware that WordPress does not allow duplicate plugins, so make sure to add unique features to your plugin.
Preparing Your Plugin
Step 1: Modify the Readme File
- Open the Readme File: This file is crucial as WordPress extracts information from it to display on the plugin page.
- Format Correctly: Make sure to follow specific formats. I’ve included a link in the resource section for the documentation on how to format the readme file.
- Use Recommended Tools:
- Generator Tool: To create a well-formatted readme file, use the generator tool provided in the resources.
- Validator Tool: Validate your readme file to catch potential errors that could lead to rejection.
Step 2: Validate the Readme File
- After pasting your readme content, run it through the validator.
- Warnings vs. Errors: Yellow warnings are just recommendations, but any errors must be addressed before proceeding.
Packaging Your Plugin
Step 3: Build the Plugin
- Command Line: Open the command line to prepare your plugin for zipping.
- Run Build Command: This optimizes the plugin for production.bashCopy code
npm run build
Step 4: Zip the Plugin
- Automated Zipping: You can use the command:bashCopy code
npm run plugin:zip
However, this method can be unreliable. - Manual Zipping: If you prefer, zip the plugin manually, ensuring you exclude the
node_modules
directory to avoid a large file size.
Submitting Your Plugin
Step 5: Create a WordPress Account
- Before uploading, create an account on the WordPress site.
Step 6: Upload Your Plugin
- After creating your account, follow the link provided in the resources to submit your plugin.