Categories
gutenberg WordPress

A simpler way to add SVGs to custom WordPress (Gutenberg) blocks using SVGR

For the past several months I’ve been developing a new course about custom WordPress block development for LinkedIn Learning. Early on in the process I started looking for a simple way to add custom SVGs to custom blocks. The solution (or more specifically a solution) was found deep inside Create React App: SVGR.

From the SVGR documentation:

SVGR transforms SVG into ready to use components. It is part of create-react-app and makes SVG integration into your React projects easy.

SVGR documentation

Unifying custom block development with @wordpress/scripts

To take full advantage of the features of both the WordPress block editor and modern JavaScript, you need to use some combination of Webpack and Babel to introduce full support for ECMAScript 2015. Configuring Webpack and Babel and all the necessary WordPress packs and everything else can be a challenge. To make things simpler, the Gutenberg team has released @wordpress/scripts aka wp-scripts, a “collection of reusable scripts for WordPress development.” This package has now been updated to include configurations for Webpack and Babel to provide a unified build process for the WordPress community.

Using SVGR in WordPress (Gutenberg) block development

In my own block development I’d been using a custom Webpack + Babel + a bunch of other stuff setup. This setup included SVGR for simplified SVG inclusion. Last week I refactored my build process to using @wordpress/scripts and in the process had to figure out how to extend the pre-packaged webpack configuration to include my custom script.

Since there’s a good chance you’ll want to add some SVG magic to your WordPress blocks, I figured I’d share my findings with you here. I’ve also added a simplified code example to the official @wordpress/scripts documentation.

By the end of this process, you’ll be able to

  • turn any SVG into a React component
  • have that SVG output inline by calling the React component
  • add the SVG as a base64 encoded image element if you want to call it directly from the src attribute inside an <img> element

For this we need two packages: @svgr/webpack and url-loader.

Here’s the full breakdown (this assumes you are already using @wordpress/scripts):

From within your project folder where package.json resides, run the following commands in terminal:

npm install @svgr/webpack --save-dev 
npm install url-loader --save-dev 

Create a new webpack.config.js file.

Require the original webpack.config.js from @wordpress/scripts:

const defaultConfig = require("./node_modules/@wordpress/scripts/config/webpack.config");

Extend the existing config with custom settings for @svgr/webpack and url-loader:

module.exports = {
  ...defaultConfig,
  module: {
    ...defaultConfig.module,
    rules: [
      ...defaultConfig.module.rules,
      {
        test: /\.svg$/,
        use: ["@svgr/webpack", "url-loader"]
      }
    ]
  }
};

Place your SVG(s) in the /src folder of your project.

In your index.js file (where you’re using registerBlockType()), import the SVG:

import customLogoURL, { ReactComponent as customLogo } from "./logo.svg"; 

Now you can call customLogoURL (the SVG transformed into a base64 encoded URI) and customLogo (the React component) from anywhere within your block definition. Example:

registerBlockType("block/myblock", {
  title: __("A Block", "myblocs"),
  icon: {
    src: customLogo // The React component
  },
  category: "regular",
  attributes: {
    blockImage: {
      type: "string",
      default: customLogoURL // The base64 encoded URI
    }
  },
  (...)
}

Cool, right? And clean and easy to read.

Stay tuned for my upcoming LinkedIn Learning course on WordPress Block Development where you’ll learn more about how to build your own custom blocks!


Cross-posted to LinkedIn Pulse.

Categories
gutenberg WordPress

Gutenberg and the Future of WordPress: Conditions for Success

NB: This article is part of a series on the new WordPress editing experience called "Gutenberg". If you are not familiar with Gutenberg, check out the first article in the series.

As the Gutenberg project moves ever closer to merging with WordPress, users, administrators, designers, developers, and core contributors are raising concerns about timelines and what will happen to the community once the merge is complete. I've been thinking about this for the past year and over the last few weeks I've had several conversations that have helped bring into focus the key conditions I think need to be in place for Gutenberg to be a success. I present them to the community to start the conversation. Please add your own voice in the comments below, on social media using the #Gutenberg hashtag, on your own blog or website, and in the GitHub repository. Every viewpoint is relevant, every voice matters.

Before we continue, be advised these are my personal opinions. As of this writing I am not a functioning member of the Gutenberg team nor am I speaking on behalf of anyone other than myself. What you'll read below does not indicate nor dictate the future course of this project, they are the conditions I personally think need to be met for the success of the project. In my opinion. Clear? Ok, you can continue:

Condition 1: Accessibility

The web was built to make content and information accessible to anyone and everyone. WordPress' core principle is to "Democratize Publishing" and a key part in achieving this is to make sure WordPress itself and the code generated by WordPress is accessible.

The first condition for the success of Gutenberg is accessibility, both on the back end and on the front end. WordPress core is ostensibly accessible, and over the past several years significant efforts have been made put accessibility at the center of every conversation about WordPress. As Gutenberg merges with core, it is imperative that accessibility is not just maintained but improved.

Web accessibility is not just good practice (an inaccessible site is a broken site) and a moral duty, it is also becoming a legal requirement in many regions. Meeting this condition is a necessity for the future success of WordPress and the millions of sites it runs.

For this condition to be met, Gutenberg and the merged version need to be able to pass independent comprehensive accessibility review.

Condition 2: Change moratorium and ample ramp-up time

During his State of the Word address at WordCamp US 2017, project lead Matt Mullenweg suggested Gutenberg would be "ready for the widest audience" in April 2018. The comment is ambiguous (view it for yourself here) and it is not clear whether he means the beta plugin is ready to be pushed to all WordPress users for testing or Gutenberg is ready for core merge or if he thinks Gutenberg will be merged in core and WordPress 5.0 will release in April. I think (hope) he means Gutenberg will be ready for full-scale testing in April and will be pushed out so people can test it before it is merged to core at that time. If I'm informed otherwise I'll update this section.

Be that as it may, the second condition for the success of Gutenberg is that the community is given enough time to prepare before WordPress is updated. To achieve this, once Gutenberg is considered ready for core merge, the Gutenberg plugin should be advertised to all WordPress users along with a training regimen, and I propose a 4-6 month moratorium on Gutenberg and core updates from the time Gutenberg is considered ready and WordPress 5.0 ships. This sounds extreme, but it is necessary for several reasons, most notably:

Gutenberg changes how WordPress works

WordPress users need time to prepare for Gutenberg. They need comprehensive documentation and training, and need time to figure out how to run their blog/website/e-commerce store/community using this new version of WordPress. This is especially important for large-scale operations like educational institutions and publishers as they typically have complex publishing processes in place that need to be updated.

Without a significant marketing push and proper documentation and training, WordPress users will feel as if their platform has been changed without their knowledge and it will cause them unnecessary hardship. Bridget Willard has written about this in more detail. A moratorium would provide ample lead-up time to ensure WordPress users and the businesses that rely on the platform have time to prepare.

Plugins and themes need to be updated in advance

Because Gutenberg changes the way WordPress works, many themes and plugins will either work differently or not work properly with the rollout. Unless they are updated in advance. A change moratorium provides enough time to allow plugin and theme authors to a) learn how to build solutions for Gutenberg, and b) roll out necessary updates in advance of the final release. The goal here is to ensure when the switch happens, WordPress seamlessly transitions from old to new and everything continues to work.

For that to happen, plugins and themes must already be updated to account for Gutenberg before WordPress updates. The alternative, to update WordPress and then be told to update a long list of plugins, or worse be told some plugins or themes will no longer work, is not tenable as it will appear to the people who use WordPress as WordPress being broken.

If/when plugins and themes are updated, they will have to invest time and money in providing documentation and training for their users to help them prepare. Which leads us back to the first point: Gutenberg changes how WordPress works.

Condition 3: A line in the sand

This is easily the most controversial point, so I'll reiterate this is my personal opinion.

The third condition for the success of Gutenberg and the WordPress of the future is for WordPress to cleanly fork itself at version 5.0. Let me explain:

Even if the two other conditions are met: Gutenberg sets a new gold standard for accessibility on the back- and front-end, and the community is granted ample time to prepare, train, reengineer, and build their businesses around Gutenberg, there will still be a large number of WordPress sites and solutions that will be negatively affected by this update. There are many reasons for this:

  • Plugins and themes that won't update for various reasons.
  • Custom setups that would need to be completely reengineered to work under Gutenberg.
  • Custom setups that are too expensive to update.
  • Processes and procedures that require expensive retraining of tens or hundreds or thousands of users.
  • Legacy systems that can't be updated to Gutenberg for various reasons.
  • your reason goes here.

Bottom line, there are valid reasons why many WordPress users and WordPress sites can't or will be unduly negatively affected by the upgrade to Gutenberg. The only responsible course of action from WordPress is to provide a clean solution for these users to opt out of the upgrade and stay on the last stable release, which will be 4.9.x. In other words, WordPress forks itself at 5.0 creating "WordPress Classic" for users and sites that can't or won't upgrade.

For this to work, WordPress Classic would need to accept a feature freeze receiving only security updates. If it evolves independently, we'll invariably end up with two incompatible solutions.

Here's the thing: If this is not done, the community will fracture and those who rely on pre-Gutenberg WordPress will either refuse to upgrade causing major security and maintenance issues, force a fork which will split the community, or abandon WordPress for other options. Neither of these outcomes are beneficial to anyone.

Benefits of a clean fork

Cleanly forking WordPress at 5.0 brings benefits for the Gutenberg project and for WordPress as a whole:

  • The requirement of backwards compatibility can be removed, or reset to 5.0 meaning WordPress' code base can finally be updated and modernized.
  • Data structures inside WordPress can be properly modularized and Gutenberg can move beyond the content blob.
  • Plugin and theme authors can ship solutions that only work for WordPress Classic or WordPress New removing the need to support both the new and the old editor.
  • PHP and other infrastructure version requirements can be updated without leaving people behind.
  • People who can't or don't want to upgrade can cleanly choose WordPress Classic as their solution.
  • If people try to install WordPress in an environment that does not support the new version, they can automatically be sent to WordPress Classic for the top-of-the-line experience we have today.

Drawbacks of a clean fork

There are significant drawbacks to forking WordPress as well:

  • WordPress would be forked, which splits the community.
  • Maintaining two versions requires twice as much work as maintaining one.
  • Eventually a fork will evolve on its own, feature freeze or not.
  • A fork provides "bad optics" as they say.

Dangers of not forking WordPress

There are significant risks to not forking WordPress, and at present we are headed straight toward all of them. Here's a small sample:

  • Not forking WordPress means the project needs to retain backwards compatibility. That means continued support for both the current (classic) editor and the ever evolving Gutenberg experience. This will hold back and eventually block future innovation and WordPress will become a monster even Dr. Frankenstein would shun.
  • The current approach to handling plugins and themes lacking Gutenberg support is to allow them to declare lack of support and force a fallback to the old editor. This will be used by plugin and theme developers who do not like Gutenberg to force WordPress to revert. Which in turn holds back future development. It also means plugin and theme developers have to ship code that supports both the classic editor and Gutenberg because any other theme or plugin may force WordPress to roll back. This issue was brought up by Kevin Hoffman brought this up during State of the Word, and the answer he got was, in my opinion, less than satisfactory (judge for yourself).
  • One of the major issues with WordPress is how it handles content. Presently all post content sits in the post table as a single blob which makes it impossible to effectively query data without querying the whole post content. To get around this problem theme and plugin developers use custom fields, but these just stash all the info in another table so we end up with two blobs. To truly meet the goals of Gutenberg, the blob needs to be broken up and the data structures of WordPress need to be rearchitected. If WordPress is not forked, this will not be possible and the current structures will eventually render the application obsolete.
  • Finally, if a clean fork is not created, parts of the community will shard off and force a fork. This will be damaging to the community as a whole because it will create an antagonistic relationship between those who support the "classic" fork and those who stay with the Gutenberg branch. With a clean fork, much of this animosity can be avoided or remedied, and we won't end up with a fractured community.

Your voice matters, and I want to hear it

Now that you know what I think needs to happen for this project to succeed, I want to know what you think. Like I said before, add your thoughts in the comments on this article, share them on social media using the #Gutenberg hashtag, publish your own articles, file issues and contribute to the project on GitHub, and keep the conversation going. I'm looking forward to having this conversation with you.


This article was cross-posted on LinkedIn Pulse.

Categories
gutenberg WordPress

WordPress is Changing. Here are 3 Things You Need to Know About Gutenberg

Everything you know about WordPress is about to change. The project codenamed "Gutenberg" is reimagining what content creation and editing on the web should look like and how it should work. Some time in 2018 the way WordPress works and the way you work with WordPress will change in a fundamental way, whether you are a visitor, a content creator, an administrator, a designer, or a developer.

Last weekend I had the privilege of presenting a talk titled "Gutenberg and the WordPress of Tomorrow" at WordCamp US in Nashville. You can view the video below and slides below. Once you're done, keep scrolling to see the three things you need to know as WordPress moves into the future.

1. Gutenberg is coming, fast. Be prepared.

If this is the first time you've heard about Gutenberg, this is the time to familiarize yourself with the project. The second half of Matt Mullenweg's State of the Word talk from WordCamp 2017 is a good place to start:

The project will probably reach maturity around April 2018 and I expect WordPress 5.0 will ship with this new interface to every WordPress site around June/July 2018. That means right now you have roughly 6 months to prepare.

Here are my recommendations:

  • Familiarize yourself with Gutenberg by installing the plugin on an experimental site.
  • Train your contributors / staff on content creation and management using Gutenberg.
  • Check with the developers of your themes and plugins that they are preparing for Gutenberg.
  • As the release gets closer, start testing your sites with Gutenberg to ensure everything works properly.

2. Gutenberg is not just an editor replacement, it changes everything!

The core concept of Gutenberg is every item you add to WordPress is a "block". Every heading, paragraph, image, blockquote, list, and other content you add is a block, and every block has unique properties and settings. That means when you create content, you can work with and customize each individual block, move those blocks around, and even make individual blocks reusable so you can build them once and use them in different locations and different views.

Notice how I said "views", not "posts and pages"? This is key: The current version of Gutenberg replaces the content editor. That's step one. Once it merges into WordPress proper, the project will expand its scope to encompass the Customizer, and eventually the way we create and mange content in WordPress will undergo a complete overhaul. Today we think of creating posts and pages. In the WordPress of Tomorrow, we will be making blocksand placing them in views. As weird as it sounds, the concept of post and pages is going away, and along with it the WordPress theme as we know it will likely fall to the wayside replaced by something all together different.

To wrap your head around this, imagine every piece of content you create as a literal building block and the environment (or view) the visitor accesses a space where you can place and organize those blocks in any combination and configuration you want. Then realize the current limitation of the browser viewport (the rectangular area within the screen you probably use to access the web) is going away thanks to everything from text-to-speech browsers to VR/AR/MR/XR.

Bottom line: The way we interact with content on the web is changing in a fundamental way and Gutenberg is what can bring WordPress into that future.

3. Gutenberg needs you!

Which brings me to the final point: Gutenberg is not ready, and the Gutenberg team needs your input and help to get the project and WordPress where it needs to go. Whether you are an absolute beginner and just started using WordPress yesterday or you have been contributing to WordPress core since the first line of code was written, your input is vital for the success of the project.

Here are some ways you can help:

These are exciting times and we are privileged to be part of a community that values every member and hears every voice. Your contributions matter. Make your voice heard!


This article was cross-posted on LinkedIn Pulse.