Categories
Development

Stylesheets in Gutenberg Blocks

Welcome back, everyone! Today we’re here to figure out how to add stylesheets in Gutenberg blocks. In our earlier Gutenberg custom blocks tutorial, we incorporated styles using a constant variable in our JavaScript. Though this method worked, it makes quickly editing or revisioning styles a real headache. Without any further ado, let’s create our new block and get started adding custom stylesheets.

stylesheets in gutenberg blocks.

Tip: Before we start, I wanted to restate this is one in a series of Gutenberg block tutorials. I assume you’ve followed along with the first tutorial to get this far. If you’re coming to this page without viewing the first tutorial, please take a look at how we have set up our blocks plugin.

Creating a New Block

Open up your IDE or editor of choice, and a terminal window if your development environment doesn’t include it. Migrate the terminal to our parent block folder, my-blocks. Once inside our plugin directory, enter the following commands into your terminal to set up our custom block folder structure alongside some required files:

mkdir styled-block cd styled-block mkdir languages mkdir styles mkdir src touch styles/style.css touch styles/editor.css touch src/index.js touch index.php

Creating Your index.php File

Now that we have our basic file structure, it’s time to configure our index file to register the block. This file should be familiar to anyone who has worked with WordPress plugins in the past. We’ll be using the index file to register our block, as well as the stylesheets to be used! Go ahead and copy the following code into your index file now:

<?php /** * Plugin Name: My Blocks Styled Block * Plugin URI: https://yourwebsite.com * Description: This is a plugin to show how to include stylesheets in a Gutenberg block. * Version: 1.0.0 * Author: Your Name * * @package my-blocks */ defined( 'ABSPATH' ) || exit; /** * Load all translations for our plugin from the MO file. */ add_action( 'init', 'my_blocks_styled_block_load_textdomain' ); function my_blocks_styled_block_load_textdomain () { load_plugin_textdomain( 'my-blocks', false, basename( __DIR__ ) . '/languages' ); } /** * Registers all block assets so that they can be enqueued through Gutenberg in * the corresponding context. * * Passes translations to JavaScript. */ function my_blocks_styled_block_register_block() { // automatically load dependencies and version $asset_file = include( plugin_dir_path( __FILE__ ) . 'build/index.asset.php'); /* Register our script we will be using to develop the plugin. Most ouf our code will be going in here! */ wp_register_script( 'my-blocks-styled-block', plugins_url('build/index.js', __FILE__), $asset_file['dependencies'], $asset_file['version'] ); /* CSS Used in the editor */ wp_register_style( 'my-blocks-styled-block-editor-styles', plugins_url( 'styles/editor.css', __FILE__ ), array( 'wp-edit-blocks' ), filemtime( plugin_dir_path( __FILE__ ) . 'styles/editor.css' ) ); /* CSS Used on the frontend */ wp_register_style( 'my-blocks-styled-block-styles', plugins_url( 'styles/style.css', __FILE__ ), array( 'wp-edit-blocks' ), filemtime( plugin_dir_path( __FILE__ ) . 'styles/style.css' ) ); register_block_type( 'my-blocks/styled-block', array( 'style' => 'my-blocks-styled-block-styles', 'editor_style' => 'my-blocks-styled-block-editor-styles', 'editor_script' => 'my-blocks-styled-block', ) ); if ( function_exists( 'wp_set_script_translations' ) ) { /** * May be extended to wp_set_script_translations( 'my-handle', 'my-domain', * plugin_dir_path( MY_PLUGIN ) . 'languages' ) ). For details see * https://make.wordpress.org/core/2018/11/09/new-javascript-i18n-support-in-wordpress/ */ wp_set_script_translations( 'my-blocks-styled-block', 'my-blocks' ); } } add_action( 'init', 'my_blocks_styled_block_register_block' );

Breaking It Down

It might look like a lot of code from here, but what’s going on is quite simple. Let’s break it all down into sections to fully understand what these functions are doing. We’ll start with the base plugin configurations, then cover registering styles. Last but not least, we’ll put it all together by registering our block.

Base Plugin Configurations

<?php /** * Plugin Name: My Blocks Styled Block * Plugin URI: https://yourwebsite.com * Description: This is a plugin to show how to include stylesheets in a Gutenberg block. * Version: 1.0.0 * Author: Your Name * * @package my-blocks */ defined( 'ABSPATH' ) || exit; /** * Load all translations for our plugin from the MO file. */ add_action( 'init', 'my_blocks_styled_block_load_textdomain' ); function my_blocks_styled_block_load_textdomain () { load_plugin_textdomain( 'my-blocks', false, basename( __DIR__ ) . '/languages' ); }

A lot of this will be familiar if you followed along with the last tutorial. We begin by adding necessary plugin information into the comment section. Next, we check if ABSPATH is defined. This is an essential security technique to ensure only WordPress can run our code directly. Finally, just like last time, we include any needed translation files. Next up? The (mostly) new stuff!

Registering Stylesheets in Gutenberg Blocks

/** * Registers all block assets so that they can be enqueued through Gutenberg in * the corresponding context. * * Passes translations to JavaScript. */ function my_blocks_styled_block_register_block() { // automatically load dependencies and version $asset_file = include( plugin_dir_path( __FILE__ ) . 'build/index.asset.php'); /* Register our script we will be using to develop the plugin. Most ouf our code will be going in here! */ wp_register_script( 'my-blocks-styled-block', plugins_url('build/index.js', __FILE__), $asset_file['dependencies'], $asset_file['version'] ); /* CSS Used on the frontend */ wp_register_style( 'my-blocks-styled-block-styles', plugins_url( 'styles/style.css', __FILE__ ), array( 'wp-edit-blocks' ), filemtime( plugin_dir_path( __FILE__ ) . 'styles/style.css' ) ); /* CSS Used in the editor */ wp_register_style( 'my-blocks-styled-block-editor-styles', plugins_url( 'styles/editor.css', __FILE__ ), array( 'wp-edit-blocks' ), filemtime( plugin_dir_path( __FILE__ ) . 'styles/editor.css' ) ); register_block_type( 'my-blocks/styled-block', array( 'style' => 'my-blocks-styled-block-styles', 'editor_style' => 'my-blocks-styled-block-editor-styles', 'editor_script' => 'my-blocks-styled-block', ) ); if ( function_exists( 'wp_set_script_translations' ) ) { /** * May be extended to wp_set_script_translations( 'my-handle', 'my-domain', * plugin_dir_path( MY_PLUGIN ) . 'languages' ) ). For details see * https://make.wordpress.org/core/2018/11/09/new-javascript-i18n-support-in-wordpress/ */ wp_set_script_translations( 'my-blocks-styled-block', 'my-blocks' ); } } add_action( 'init', 'my_blocks_styled_block_register_block' );

Finally, we prepare all our required files and actually register our block. Most of this code was also used in our first block, but we’ve added some vital function calls to register our stylesheets. We have to call wp_register_styles() twice, once for the frontend, and once for the editor.

Adding Styles to the Frontend

Everything is looking great for our index file, so it’s time to move into the CSS. We’ll add the frontend styles first. That’s the same way WordPress will enqueue the stylesheets, allowing editor styles to override frontend defaults!

Open styles/style.css in your IDE and add the following code:

.wp-block-my-blocks-styled-block { color: darkred; background: #fcc; border: 2px solid #c99; padding: 20px; }

Nothing fancy here, just a dark red font on a lighter red background. We’ve also applied a border and some padding to help things stand out further.

Adding Styles to the Editor

Sometimes, you may want your content to display differently in the editor. Since we’ve added a specific editor stylesheet, we can add our own custom CSS only seen in the Gutenberg editor.

Go ahead and open styles/editor.scss in your IDE. add the following code:

.wp-block-my-blocks-styled-block { color: green; background: #cfc; border: 2px solid #9c9; padding: 20px; }

This time we’re going with a minty green to differentiate from the frontend. With all our CSS input, you’re ready to set up your JSON package file.

Configure JSON Package File with NPM

Make sure your terminal is open within the plugin folder my-blocks/styled-block. Begin building your package file with npm init. You’ll be greeted with a small wizard to help set up your file. use the options provided below.

package name: (styled-block) version: (1.0.0) description: A block to demonstrate styles. entry point: (index.js) build/index.js test command: git repository: keywords: author: Your Name license: (ISC)

After a few moments, NPM should generate your package file! Next, we need to add some dependencies to our package.

npm install --save-dev --save-exact @wordpress/scripts

Once installed, you’ll notice a node_modules folder in our plugin. In order to make the most of these new files, we need to open package.json in our IDE. With our package open, find the “scripts” section. It should look the same as below:

"scripts": { "test": "echo \"Error: no test specified\" && exit 1", },

Let’s fix that up to use our new dependencies. Change the scripts section to the following:

"scripts": { "build": "wp-scripts build", "start": "wp-scripts start", "format:js": "wp-scripts format-js", "lint:js": "wp-scripts lint-js", "packages-update": "wp-scripts packages-update" },

Finally, let’s create our index.asset.php file with our build command. Enter the following in the terminal.

npm run build

Creating Block Output JavaScript

With everything registered and styled, we can finally move on to the actual output of our block. Open the src/index.js file in your IDE and input the following code:

import { __ } from '@wordpress/i18n'; import { registerBlockType } from '@wordpress/blocks'; registerBlockType( 'my-blocks/styled-block', { title: __( 'Styled Block', 'my-blocks' ), icon: 'album', category: 'my-blocks', example: {}, edit(props) { return ( <div className={props.className}> Styled Block in the editor. </div> ) }, save() { return ( <div> Styled Block Front </div> ) }, } );

Once again, most of this should look very similar to our first block. We start by importing the relevant components of wp-scripts needed for our output. Next up we begin to register our block with Gutenberg and set some display options. Notice we’ve created a custom category to hold our growing family of blocks! Our edit method gets passed in the props argument, giving access to our blocks className among many other things. From here it’s just a simple div output giving a shoutout from the editor. Last but not least, our save method will show output to the frontend.

Leave a Reply

Your email address will not be published. Required fields are marked *