Creating Inspector Controls for Shortcode attributes – Part 1

This is next part in the series of Converting Shortcodes to Gutenberg Blocks.

Shortcodes have been part of WordPress for a long time. As the new block editor is gaining users and popularity, converting these shortcodes to blocks will be helpful. Gutenberg blocks are not only useful for creating custom page layouts, but also make the website building experience better.

When Gutenberg blocks can be used in place of shotcodes, it improves the overall user experience. As we are making this transition to blocks, we need to pay attention and make sure that the inspector controls are user friendly.

When converting a shortcode to a block, one of the first things to do is to figure out how you want to display the options in the sidebar. There is no one size fits all option here. The type of user interface we want to show ideally depends on the type of attribute.

I will use the business directory block as an example as it has many different types of attributes. Each attribute is shown in the Inspector Controls to give the user finer control over displaying their business directory listings.

Controls for simple list attributes

Some of the attributes like format, text, orderby, etc were easy to build in the block sidebar. These have a few static options to choose from and could be put into a select dropdown.

Options in the Shortcode:

'format' => 'list',  // options: list, grid2, grid3, grid4, responsive
'text' => 'excerpt', // options: excerpt, description, none
'orderby' => 'title', // options: date, modified, menu_order, rand, membership_level

Format options control in the block – all the available options are listed in the SelectControl.

const formatOptions = [
    { label: 'List', value: 'list' },
    { label: '2 Columns', value: 'grid2' },
    { label: '3 Columns', value: 'grid3' },
    { label: '4 Columns', value: 'grid4' },
    { label: 'Responsive', value: 'responsive' },
 ];
<SelectControl
    label="Directory Layout"
    value={ format }
    options= { formatOptions }
    onChange = {setDirectoryLayout}
/>
const setDirectoryLayout = format => {
    props.setAttributes( { format } );
};

Options with boolean values in the shortcode

Many of the shortcodes we use have attributes that take in boolean options – true or false. It might also be a ‘yes’ or ‘no’ to make it easier for users to understand and use in the shortcodes. The best way to display them in the block sidebar, is to use a toggle button. You can also use a simple dropdown which is easier, but I feel a toggle button is more intuitive.

The business directory shortcode has the option to display the alphabet list at the top so that businesses can be sorted by their first letter.

Image showing the businesses list with the option to sort by first letter

The shortcode has it as a Yes or No option. In the block, the option can be simply switched on or off using a toggle button.

'alpha'	=> 'no',	//options: yes, no
'show_category_filter' => 'no', //options: yes, no

Toggle options in the block inspector controls.

The toggle button did present a couple of challenges. The toggle button gives the output as true or false, but our shortcode needs the values ‘yes’ or ‘no’. So, the true or false values need to be converted to string values before being passed into our shortcode function.

Another issue was that the toggle attribute needs to be the type ‘boolean’ and the shortcode attribute was the type ‘string’.

One of the important things to remember when converting shortcode to blocks is that we need to keep the name and the type of the attribute the same. As the original attribute cannot be modified in the block, I added another attribute ‘alphaToggle which is a boolean.

alphaToggle: {
  type: 'boolean',
  default: false,
},

The toggle button is displayed using the alphaToggle. When the option is toggled, the alpha option is set which gets passed onto the shortcode function.

<PanelRow>
    <ToggleControl
	label={ __( 'Enable Alpha Search' ) }
	checked={ alphaToggle }
        onChange = {setAlpha}
    />
</PanelRow>

const setAlpha = alphaToggle =>{
        props.setAttributes({alphaToggle})
        !! alphaToggle ? 
        __( props.setAttributes({alpha: 'yes'}) ) : __( 
        props.setAttributes({alpha: 'no'}) );
        
    };

This just needed a little bit of tweaking to make it more user friendly and intuitive. I also feel that the toggle buttons are easier to use than a dropdown sometimes as we can visually see which ones are “on” and which ones are “off”.

In the next part, I will cover the dynamic dropdowns for custom taxonomies and displaying toggle buttons for each option in a single shortcode attribute.

Block Editor Updates in WP 5.5

WordPress 5.5 released on August 11th, features a few big updates for the block editor. The editor interface has some noticeable changes. The block directory is now available to install individual blocks with a single click along with the block patterns which provide a few layout options.

Editor Interface

The block editor interface has been improved a lot. It is more structured, with bigger buttons and a clean interface. The blocks don’t seem to be cluttered anymore.

The ‘Add Button (+)’ on the top shows the blocks, block patterns and reusable blocks. In the previous version, the blocks were shown sorted by category in an accordion, but now though the blocks are displayed by category, they are not in an accordion anymore. I liked the accordion way of displaying the blocks. It was easier to get to the specific blocks I needed.

The list of blocks looks less cluttered, but I would have liked if the accordion didn’t go away.

Block Menu in WP 5.4

Block Menu in WP 5.4

Block Menu in WP 5.5

Block Menu in WP 5.5

The add button next to the blocks in the editor shows recently used blocks and an option to search for blocks or browse all the blocks.

Easy to preview posts in multiple device widths

There is now an option to preview your post in Desktop, Tablet or Mobile inside the editor making it easy to build responsive pages.

Tablet preview in editor
Mobile preview in editor

Select parent blocks easily

One thing that annoyed me in the previous version is not being able to select the parent block easily. This has been made really easy in WP 5.5. You can just hover over the block toolbar to see the parent block and select it.

Moving Blocks

Moving blocks is a little different in this version. The previous version had a clear handle next to the block to move it. That handle is not available now, but you can use the up/down arrows or the ‘Move To’ option to move the blocks.

With the Up/Down arrows, click and hold on the arrows in the toolbar. That lets you move the block around.

There is a ‘Move To’ option you can see when you click on the three dots to the right in the block toolbar. Click on the ‘Move To’ option and use the arrow keys on the keyboard to move the block.

You can also get to the ‘Move To’ option entirely using the keyboard.

Block Directory

This is one of the cool features of the editor in this version. Block directory is similar to the WordPress plugin directory, but just for blocks. Until now, if we wanted to find a new block to use, we had to search through the available plugins and install them. These plugins usually have multiple blocks and even though we don’t need all those blocks, they are on our site as part of the plugin.

Block directory makes it easy to search for the particular block we need and install it without leaving the editor. These blocks are essentially plugins which can be found in the plugins page and deactivated and deleted from that page if we don’t need them.

Currently, there are only a few blocks available in the block directory, but the list is growing.

Block Patterns

Block patterns are groups of blocks that can be added to your post or page with a single click. Once you add the pattern, you can edit it as you see fit. These patterns give you simple layouts using which you can quickly build page and post layouts.

Themes and plugins can add new block patterns too which will give us more options to build easy page layouts.

Block Patterns in WP 5.5

Inline image editing

I think this is one of the best features of this version. Being able to edit images inline in the editor makes it very easy for the users. You can now crop rotate and zoom the images after you add the image to the editor.

After you add the image, you can see a crop button in the toolbar. Clicking on the crop button gives you options to zoom in, rotate or change the aspect ratio of the image.

After editing the image, click ‘apply’ to save the changes. The image gets saved as a new image.

Let me know what your favorite feature of this release is in the comments!

Styling CSS grid responsive layouts based on the number of columns on the page

Building responsive layouts using CSS Grid and Flexbox is easy. Few lines of CSS and the columns resize nicely based on the width of the page. CSS Grid or Flexbox takes care of resizing and the columns nicely stack as needed in smaller view ports. We can style these columns using media queries for different browser widths. If we want to add styles based on the number of columns showing on the page though, we need to use JavaScript.

When I was working on converting the Business Directory shortcode to a Gutenberg block, we added options to select the image size. This was a new option which was not in the shortcode. So, the users could choose the number of columns, the image to display (featured image or logo) and the size of the image along with other options while displaying their business directory listings.

They have the option to choose from 1, 2, 3 or 4 column layout or a responsive layout. When it came to styling the images and the text around it, it was not easy. We had to maintain consistency between the specific column layouts and the responsive layout.

The columns in the responsive layouts change based on the width of the page or the content width. We wanted the listings to look consistent in all formats. If the page had only one column, it should show similar to the one column layout, and if the page had 2, 3 or 4 columns, it should show similar to the other column layouts respectively.

This could probably be done using media queries, but it is not easy. The number of columns showing on the page depends on the width of the device and the with of  the page itself, or to be specific, the content width of the page. If we used the Twenty Twenty theme with the default page layout, even on a desktop, the content width is smaller and the number of columns would be different when using the responsive layout.

Business Directory layouts with default and full width pages

Business Directory listings with Twenty Twenty theme using the default layout
Business Directory listings with Twenty Twenty theme using the full width layout

Adding custom classes using JavaScript

To make the styling of the responsive columns easier, I used JavaScript to add specific classes to the responsive columns. gridColumnCount gives us the number of columns being displayed on the page. The outputGridData function adds the desired classes the specific selector. This function is being called when the page loads and also when the browsers is resized. So, the columnCount gets updated when the page width changes.

function getGridData () {
  // calc computed style
const gridComputedStyle = window.getComputedStyle(businesslist);

  return {
    // get number of grid rows
    gridRowCount: gridComputedStyle.getPropertyValue("grid-template-rows").split(" ").length,
    // get number of grid columns
    gridColumnCount: gridComputedStyle.getPropertyValue("grid-template-columns").split(" ").length,
    // get grid row sizes
    gridRowSizes: gridComputedStyle.getPropertyValue("grid-template-rows").split(" ").map(parseFloat),
    // get grid column sizes
    gridColumnSizes: gridComputedStyle.getPropertyValue("grid-template-columns").split(" ").map(parseFloat)
  }
}

window.addEventListener("DOMContentLoaded", outputGridData);
window.addEventListener("resize", outputGridData);

function outputGridData () {
  const gridData = getGridData();
  const columnCount = gridData.gridColumnCount;
  var images = document.querySelectorAll("#businesslist.responsive.cd_block .business .description a");
  //alert(images);
  for (i = 0; i < images.length; ++i) {
    images[i].className = "grid"+columnCount;
  }
}

The code adds the class grid1, grid2 etc to the specific selector. In this case, it is the “a” tag that holds the featured image or the logo. Once the classes are in place, adding styles is simple.

This ensures that no matter the page width, content width or the device width, the layouts will be consistent based on the number of columns being displayed. The image styles are dependent on the number of columns being displayed on the page. If the screen width is 1200px, but only two columns are displayed, images get floated to the left and the content floats around it.

Converting a Shortcode to a Gutenberg block

WordPress shortcodes make it easy to add complex code to the pages. Now that the new editor is here to stay and we are all getting used to the new editor, it is important to make sure that the code that was available as shortcodes should now be given to the users as blocks. Converting the shortcodes to blocks makes it more visual and much easier to use. It also gives the users a better experience as they do not need to remember all the shortcode parameters or keep referring the docs as they set up their sites.

Converting the shortcodes to Gutenberg blocks is fairly easy, but it does require a bit of initial setup to build the blocks.

Setting up your plugin for Gutenberg blocks

The first step is to setup the development environment. The WordPress documentation here gives a lot of information on setting up the initial JS build – https://developer.wordpress.org/block-editor/tutorials/javascript/js-build-setup/

This setup is almost the same whether you are starting to write a new plugin or adding Gutenberg to an existing plugin.

Once the setup is done, it is time to build our block that will work in place of the shortcode.

Top ↑

The plugin folder structure

chamber-dashboard-business-directory
│   cdash-business-directory.php
│  
├───blocks
│       cdash_bd_block.php
│       cdash_block_functions.php
│       cdash_logo_gallery.php
│      
├───build
│       index.asset.php
│       index.js
│       index.js.map
│      
│          
├───shortcodes
│       business_directory_shortcode.php
│      
├───src
│   │   block.json
│   │   dependencies.js
│   │   edit.js
│   │   icon.js
│   │   index.js
│   │   inspectorControls.js
│   │  
│   ├───business_directory_block
│   │       edit.js
│   │       icon.js
│   │       index.js
│   │       inspectorControls.js
│   │      
│   └───logo_gallery_block
│           edit.js
│           index.js
│          
           

After setting up the initial JS build, you will now have the folders /src and /build in your plugins root folder. The src folder will hold all of your block code. It is best to create another folder blocks in the root folder of your plugin for all the block related functions. This will keep our blocks code separate.

Since, I wanted to create multiple blocks in the Business Directory plugin, I created folders inside the src block. The business_directory_block and the logo_gallery_block have the code for the respective blocks. Creating a folder for each block is better to keep the code separate and less cluttered.

Each folder has an index.js which includes the actual block code. Since @wordpress/scripts package is going to look for our block code in the /src/index.js file, we need to add the index.js files for each block here.

import './business_directory_block/index.js';
import './logo_gallery_block/index.js';

Using the shortcode function

The easiest way to convert the shortcode to a block is to pass all the block attributes to the same function that is used for the shortcode.

In the Chamber Dashboard Business Directory plugin we have a shortcode that displays all the business listings. There are many parameters used with the shortcode to control what and how the listings are displayed.

Since we have all the parameters and the styles working like we want in the shortcode, it was just easier to use the shortcode function for the block as well. Also, if there are users who are still using the classic editor, they need the shortcode to exist. So, using the same function means that it is easier to maintain both the shortcode and the block.

Creating the block

Inside the business_directory_block/index.js, add the code to create the block using registerBlockType.

/**
 * Block dependencies
 */

import edit from './edit';

import { registerBlockType } from '@wordpress/blocks';
import { __ } from '@wordpress/i18n';
import { dateI18n, format, __experimentalGetSettings } from '@wordpress/date';
import { setState } from '@wordpress/compose';

registerBlockType( 'cdash-bd-blocks/business-directory', {
    title: 'Display Business Directory',
    icon: 'store',
    category: 'cd-blocks',
    attributes: {
        format: {
            type: 'string',
            default: 'grid3',
        },
        perpage:{
            type: 'number',
            default: -1,
        },
        categoryArray:{
            type: 'array',
            default: [],
        },
        category:{
            type: 'string',
            default: '',
        },
    },
    edit: edit,
    save() {
        // Rendering in PHP
        return null;
    },
} );

While creating the block, it is important to remember that all the parameters or attributes of the shortcode should be added in the block attributes section. Since we are using the same function as the shortcode, the attribute names should be the same in both the shortcode and the block.

The edit function

Next, we need to add the edit function for the block in edit.js. Here are the necessary dependencies for the edit function

import ServerSideRender from '@wordpress/server-side-render';
import { __ } from '@wordpress/i18n';
import { SelectControl, 
    Toolbar,
    Button,
    Tooltip,
    PanelBody,
    PanelRow,
    FormToggle,
    ToggleControl,
    ToolbarGroup,
    Disabled, 
    RadioControl,
    RangeControl,
    FontSizePicker } from '@wordpress/components';

    import {
        RichText,
        AlignmentToolbar,
        BlockControls,
        BlockAlignmentToolbar,
        InspectorControls,
        InnerBlocks,
        withColors,
        PanelColorSettings,
        getColorClassName
    } from '@wordpress/editor'
    ;
import { withSelect, widthDispatch } from '@wordpress/data';

const {
    withState
} = wp.compose;

The edit part of the block with inspector controls and server side render.

const formatOptions = [
    { label: 'List', value: 'list' },
    { label: '2 Columns', value: 'grid2' },
    { label: '3 Columns', value: 'grid3' },
    { label: '4 Columns', value: 'grid4' },
    { label: 'Responsive', value: 'responsive' },
 ];
const categoryOptions = [
    { label: 'Select one or more categories', value: null }
];

wp.apiFetch({path: "/wp/v2/business_category?per_page=100"}).then(posts => {
    jQuery.each( posts, function( key, val ) {
        categoryOptions.push({label: val.name, value: val.slug});
    });
}).catch( 

)
const edit = props => {
    const {attributes: {format, categoryArray, category, perpage, }, className, setAttributes } = props;

    const setDirectoryLayout = format => {
        props.setAttributes( { format } );
    };

    const setCategories = categoryArray => {
        props.setAttributes( { categoryArray} );
        console.log(categoryArray);
    };

    const inspectorControls = (
        <InspectorControls key="inspector">
            <PanelBody title={ __( 'Formatting Options' )}>
                <PanelRow>
                    <SelectControl
                        label="Directory Layout"
                        value={ format }
                        options= { formatOptions }
                        /*onChange={ ( nextValue ) =>
                            setAttributes( { format:  nextValue } )
                        }*/
                        onChange = {setDirectoryLayout}
                    />
                </PanelRow>
                <PanelRow>
                <RangeControl
                    label="Number of Businesses per page"
                    min={-1 }
                    max={ 50 }
                    onChange={ ( value ) => setAttributes( { perpage: value} ) }
                    value={ perpage }
                    initialPosition = { -1 }
                    allowReset = "true"
                />
                </PanelRow>
            <PanelBody title={ __( 'Limit By:' )} initialOpen={ false }>
                <PanelRow>
                    <SelectControl 
                        multiple
                        label = "Categories"
                        value = {categoryArray}
                        options = {categoryOptions}
                        onChange = {setCategories}
                    />
                </PanelRow>
            </PanelBody>
        </InspectorControls>
    );
    return [
        <div className={ props.className }>
            <ServerSideRender
                block="cdash-bd-blocks/business-directory"
                attributes = {props.attributes}
            />
            { inspectorControls }
            <div className="businesslist">
                
            </div>
        </div>
    ];
};

export default edit;

The ServerSideRender allows us to render a preview of the dynamic block in the editor. Since it is best to use this for blocks that render heavily on existing PHP functions, it is perfect for this particular block. More info on ServerSideRender can be found here.

Inspector Controls

The edit function has the inspector controls for the block attributes. These controls can be used to modify the shortcode attributes. The block code shown above only shows four attributes for the purpose of this post. The actual shortcode has a lot more parameters.

There is an option to select the format which determines the number of columns for the business directory layout, an option to select one or more categories (which are custom taxonomies in this case) and an option to limit the number of businesses shown per page.

The format and the perpage options are simple dropdowns which pass the selected option to the shortcode function.

The category attribute in the shortcode is a string where you can pass multiple category slugs separated with a comma. To give the option to choose multiple categories, we need to have an array. So, I created a new attribute called ‘categoryArray’ which is an empty array by default. This stores the multiple selected categories.

In the php callback function, the values from the categoryArray are passed to the category attribute as comma separated string.

ServerSideRender uses the block’s call back function. Since we are passing attributes to the ServerSideRender, we need to register the block and its attributes in php.

PHP Callback function

//Business Directory Shortcode rendering
if ( function_exists( 'register_block_type' ) ) {
    // Hook server side rendering into render callback
  register_block_type(
      'cdash-bd-blocks/business-directory', [
          'render_callback' => 'cdash_bus_directory_block_callback',
          'attributes'  => array(
              'cd_block'  => array(
                  'type'  => 'string',
                  'default' => 'yes',
              ),
              'format'    => array(
                  'type'  => 'string',
                  'default'   => 'grid3',
              ),
              'categoryArray'    => array(
                  'type'  => 'array',
                  'default'   => [],
                  'items'   => [
                      'type' => 'string',
                  ],
              ),
              'category'    => array(
                  'type'  => 'string',
                  'default'   => '',
              ),
          ),
      ]
  );
}

function cdash_bus_directory_block_callback($attributes){
  if(isset($attributes['categoryArray']) && '' != $attributes['categoryArray']){
      $attributes['category'] = $attributes['categoryArray'];
  }

  $business_listings = cdash_business_directory_shortcode($attributes);

  return $business_listings;

}

The cdash_business_directory_shortcode is the function that renders the directory listings through the shortcode. We are just calling the same function and passing in all the attributes from the block into the function.

This will display the block with the business listings with the default values. When one of the values is changed using the inspector controls in the block settings, those values are passed to the shortcode function and the front end display is modified accordingly.

Working Business Directory block:

Get tips and tutorials on using the new block editor, WordPress themes and plugins!

Food Blog layout using the block editor

This food blog home page layout is a simple layout that works well for the home page of a food blog.

This has been put together using the TwentyTwenty theme and the block editor. TwentyTwenty is the default WordPress theme and has awesome support for the block editor.

Food blog layout with Gutenberg blocks
Food blog layout (click on the image to see the entire page layout)

The layout has multiple blocks that include some of the core WordPress blocks and some blocks from other block plugins.

The colors in this layout are very neutral and help bring out the vibrant colors of the recipe images.

Click on the image to see the entire page layout.

Blocks used for this layout

Header image using the TwentyTwenty theme cover page layout.

The “Cover Template” from the TwentyTwenty theme was used for this page. The header image is the featured image added to the page. The overlay color is set in the theme custom settings by going to Appearance->Customize.

The background color of the page can also be set in the customizer.

Category sections

The next section was created by using a group block that contains 3 columns, created using the columns block. The group block has a different background color than the page background which makes it stand out in contrast.

Each column has an “Advanced Heading” block from Kadence blocks plugin, an image block and a button block.

Category sections group block for the food blog layout.

The advanced heading block provides options to set a custom font (font family) along with font size and line height. The font I used for the heading here is ‘Alex Brush’ which is a Google Font. This block also provides various other options like text-shadow and margins. Although the layout shown here does not have a text-shadow or a margin, it is easy to add them.

The buttons in this block can link to recipe categories like lunch, snack etc. This would be an easy way for the visitors to find what they need. Usually, when a visitor comes to a food blog, it is through a specific recipe link, but if they do land on the home page, this is an ideal way to send them to browse more recipes.

Media and text block - food blog layout

Call to action block – using the Media&Text block

The cooking workshops section was created using a Media&Text. The media part of the block can have an image or a video and the text part of the block can have multiple blocks if needed.

The text part of the block here shows and ‘Advanced Heading’ block from Kadence blocks, paragraph and button blocks. The heading has the same font as the section above it.

The button here is a call to action button that can be linked to a page. This block is ideal for a prize giveaway or as a link to your cooking videos. Save this block as a reusable block and use on other pages easily.

Latest Posts Block

The latest blog posts section is another group block with an ‘Advanced Heading’ block and a ‘Posts’ block from Stackable blocks plugin.

The block here displays the posts from the food category. If you add this layout to your page, make sure to select a category for the posts here.

Latest posts block as a group in the food blog layout

The advanced heading is similar to the other heading blocks and uses the same font.

The Posts block from Stackable, has more options compared to the ‘Latest Posts’ block.

Email subscription block for the food blog layout

Email Subscription Block

The email subscription block uses columns with a paragraph block on the left and an email newsletter block from ‘Atomic Blocks’ on the right.

Atomic blocks provides with an email newsletter block that is connected to Mailchimp. To use this block, you need to connect your Mailchimp account by saving the api key in the plugin settings.

You can select the Mailchimp list when you add the block to the page.

The footer has space to add widgets. The search widget was added to the left and the on the right side is an image gallery of the featured images of the recipe posts. These images are linked to the posts.

Footer layout using the TwentyTwenty theme.

Adding this layout to your site

Modify this layout easily to match your site’s colors and fonts. You can download the code and add it to your page. Just copy the code and paste it into the code editor of your page.

If you are not sure about how to add the layout code to your page, view the video below.

Make sure you have all the necessary block plugins required for this layout to work. This layout uses blocks from Kadence Blocks, Atomic Blocks and Stackable along with the core WordPress blocks.

Fun Scrapbook Layout with Gutenberg

Scrap-booking has been my hobby since 2005. It is relaxing and I get to re-live all the fun while putting the pictures together.

I tried a few digital scrapbooks and I loved the ease with which we can put together a page. Adding those digital layouts as part of our blog is easy, but if I want to change something, it is not a simple process.

The new Gutenberg editor now offers ways for us to incorporate cool layouts in our posts and pages. I have been experimenting a lot with Gutenberg lately and I created this simple layout to display some travel pictures of our recent trip.

The Final layout

Simple Gutenberg layout to display images

The above layout requires a few Gutenberg blocks and a little bit of custom CSS. Here is how I built this layout.

Blocks used for the layout

The entire layout is a ‘Group Block’ with a cover block and columns block inside. The columns block has three columns. The cover block holds the big image and the three columns hold the 3 small images.

Group Block Settings

The nice thing about the group block is that we can add a custom background color. I chose the same color as the background color of my site. I added a custom css class to the group block – ‘fun_times_group’ and chose the ‘wide width’ option.

The cover block inside the group block has the main image as the background. The cover block was also set to ‘wide width’ with all other default settings, a solid color overlay with 30% background opacity.

Inside the cover block, I added a heading block and columns block with six columns. For the heading block, I used the ‘Advanced Heading Block‘ form Kadence Blocks plugin. This plugin offers some advanced options for many of the core blocks and some nice to use layouts as well. The advanced heading blocks let me customize the font. The regular heading font coming from the theme is okay, but since this was supposed to be a fun layout, I opted for a fancy font.

The font I used here is the ‘Bad Script’ with font size of 80px and a line height of 87px. The text is center aligned. The rest of the settings were left as default.

Advanced Heading block settings
Advanced Heading block typography settings

The six columns below the cover block are the ones that give the stripes on the big image. I added a custom class to the columns block (the one that is inside the cover block) – ‘top_columns’. Each of these columns has a left border and the last column also has a right border 10px wide. I chose the background color of the group block as the border color for the columns. This shows up nicely as stripes over the image. Everything else is done with CSS. I adjusted the z-index values to show the font over the stripes.

The lower columns block (the one with 3 columns) has the custom class ’tilted_images’. I added an image to to each of the columns and added custom classes to the left and right images – ‘left_image’ and ‘right_image’ respectively. The image tilt is done with the CSS transform property.

Custom CSS

The custom CSS used for the image rotation and the stripes can be added in the Appearance -> Customize -> Custom CSS.

/*Adjust the minimum height, top and bottom margins to get the stripes to span the entire height of the image*/
.top_columns .wp-block-column{
    border-left: #5C5C42 10px solid; /*this is the color of the stripes*/
    min-height: 500px;
    margin-top: -50%;
    margin-bottom: -20%;
    z-index:-10;
}

.top_columns .wp-block-column:last-child{
	border-right:#5C5C42 10px solid; /*This is the last stripe to the right*/
}

/*This moves all the 3 images to the top*/
.fun_times_group .wp-block-columns.tilted_images{
	margin-top:-10%;
}

.tilted_images .wp-block-column{
	z-index:10;
}

.tilted_images .wp-block-image.left_image{
	transform: rotate(-10deg);
}

.tilted_images .wp-block-image.right_image{
	transform: rotate(5deg);
}

Gutenberg (Block Editor) for Small Businesses

The block editor also called as Gutenberg was merged into WP core in Dec 2018. It was made the default editor as part of WP 5.0. I have been testing the editor even before it was released and I love it. In the past few months, there have been a few improvements and updates to the editor. Though there is a lot of room for improvement, there are a bunch of cool features that we can use now to create nice pages and posts.

Most WP users have used the block editor at least a few times by now. The WP users have mixed feelings about the new editor. Some people like it so much that they never want to see the old editor ever again. Some people hate it that they installed the classic editor plugin and are happy. Then there are people who don’t like it as much, but don’t mind using it.

Some of the cool features of the block editor

The block editor has all the features of the classic editor and some more. Here are some of the neat features of the block editor:

  • Can change the layout of your posts and pages. With the classic editor, you can only do what your theme template allows you to do. Now, you can move the content around to achieve a different layout.
  • The classic editor did not have the table option by default. With the block editor, adding tables is a breeze. You can not only add a table with a single click, you can also style it.
  • Adding columns to your posts or pages is now really simple which gives you the ability to modify the page layout.
  • You can add widgets in your posts and pages. The widgets usually live on the sidebar, but they have a lot of useful information. With responsive websites being the norm, the sidebars usually get pushed to the bottom or entirely disappear on tablets and phones. So, being able to add widgets to your posts is a huge advantage. You can add your latest posts from a certain category, a calendar, search bar or a RSS feed link.
  • If you have a WooCommerce store, adding latest products or products that are on sale is a breeze. You can add a bunch of different products with the click of a button. It makes it very easy to add products as part of your promotional post or page. Earlier this was possible by using shortcodes, but the blocks make it easier.
  • You can also save your blocks to be reused at other places which means that you can create an ad or a promotional item once and reuse it on other posts and pages. If you change the reusable block once, it gets updated everywhere. Read more about reusable blocks.

Managing the blocks in the page/post editor

There are many blocks being added with every new release and with so many plugins adding their own blocks to the list, it can become overwhelming. Sometimes, you might feel like there are too many blocks, and in that case, you can hide them through the block manager. If there are certain blocks that you don’t use at all, you can simply choose not to display them in the list of blocks.

To access the block manager, click on the three vertical dots on the top right corner and select the ‘Block Manager’. In the Block Manager, uncheck the blocks that you do not want to show up in your editor.

Block Manager Popup

If you want some distraction free writing mode in your editor, you can choose to display all the block and document tools at the top of your editor.

Setting the toolbar to be at the top
Toolbar at the top of the editor

How does the block editor help small businesses?

If you are just getting started with your business or if you are a local small business owner, you are most likely trying to keep the expenses low by doing most of the website related stuff yourselves. This is one of the big reasons WordPress is a good platform for you. It gives you the ability to setup and manage your websites at a low cost.

Before the block editor, you needed a page builder or theme templates to add a new page with a different layout. With the new block editor, that is made very easy. You can now easily setup a promotional landing page or ads within minutes and change it as you see fit. Ofcourse, with just the block editor, the possibilities are limited, but there are plugins that provide amazing layout options which make it very easy. Some of the page builders also now work with the new editor which give you more possibilities. You can find those plugins at the end of this post.

With the new editor and a couple of supported plugins, you do not need to depend on a web developer to build you new theme templates. This will save you time and money. It will be worth it, even though it has a small learning curve.

Read why small businesses need to have a strong online presence?

Page Layouts

Creating page layouts is very easy with the new editor. There are a number of layouts that you can create.

Here are some examples of some simple page layouts that you can create in a matter of minutes that will increase your page views and ultimately result in more clients.

  • Promotional sales
  • Portfolio layout

Do I need a Gutenberg ready theme?

With the block editor being drastically different from the classic editor, the themes and plugins need to add support for the new editor. The editor works with all themes by default, but, some of the features like full width will not be available unless the themes declare support for those features.

Displaying images in full width mode is one of the nice features of the block editor. The themes need to declare explicit support for this feature. Below are screenshots from editors that show the if the theme supports the wide width and full width modes.

Gutenberg ready themes also take into account the color palette of the site. Each theme has a set of colors that determines the appearance of the site. Since with the new block editor, you can choose some of the background and font colors, it is important that the color palette is limited to the ones that work well with the theme. You can still choose a custom color by clicking on the ‘Custom Color’ link.

Regular Color Palette in the block editor
Regular color palette
Theme specific color palette.
Theme specific color palette

How to find a Gutenberg ready theme?

Themes that provide complete support to Gutenberg are tagged as ‘Gutenberg Ready’ in the themes repo. You can go to wordpress.org/themes and search for ‘Gutenberg Ready’ in the search bar.

Alternatively, you can use the feature filter to filter for ‘Block Editor Styles’. Both these searches might not give you the same results.

Read more on how to choose a theme for your WordPress site?

Other plugins that add features to the block editor

There are a number of plugins that add more blocks to your default editor. These blocks give you additional functionality. Each of these plugins provides enhanced block features which gives you more power to create custom page layouts.

If you would like to learn more about how to use the editor, you can find some amazing tutorials here – https://gutenberghub.com/

Custom Blocks with Advanced Custom Fields

Advanced Custom Fields is an amazing plugin that I have been using for a while. It makes it so easy to build extra fields for WordPress sites. So, when the custom blocks feature came out, I just had to try.

Here is the first block I built to display a post from a custom post type.

Featured Business block
in the editor
Featured Business Block Settings

Creating the block using acf_register_block

//Custom blocks using ACF
add_action('acf/init', 'my_acf_init');
function my_acf_init() {
    // check function exists
	if( function_exists('acf_register_block') ) {

            acf_register_block(array(
              'name'  => 'featured-business',
              'title' => __('Featured Business ACF'),
              'description' => __('A block that display custom post type posts.'),
              'render_callback' => 'my_acf_block_render_callback',
              'category'  => 'formatting',
              'icon'  => 'admin-comments',
              'keywords'  => array('custom post type', 'custom post'),
          ));
     }
}

‘my_acf_block_render_callback‘ function calls the template to display the block content on the front end. The $slug will be the same as the ‘name’ specified in the acf_register_block. The ‘acf_register_block’ and the callback function can be added to your theme’s functions.php.

function my_acf_block_render_callback( $block ) {

	// convert name ("acf/featured-business") into path friendly slug 
        ("featured-business")
	$slug = str_replace('acf/', '', $block['name']);

	// include a template part from within the "template-parts/block" 
       folder
	if( file_exists( get_theme_file_path("/template-parts/block/content- 
            {$slug}.php") ) ) {
		include( get_theme_file_path("/template-parts/block/content- 
               {$slug}.php") );
	}
}

Create the fields

I created three fields for this block. The first one is the ‘Title’ field, the second is the drop down to select a post from the business custom post type and the third field to provide an option to display ‘Featured Image’ of the post selected.

Fields in the Featured Business block

The ‘Block Title’ is a text field and and the “Display Featured Image’ is a radio button field. The ‘Select a Business’ field is a ‘Post Object’ field type and I am filtering by the post type ‘business’.

Creating a template to display the block on the front end.

The template can be placed in template-parts/block/content-featured-business.php. The file name should be content-$slug.php. The block title is displayed as a H3 tag, the post title is liked to the actual post. If display featured image is set to ‘yes’, then a featured image is displayed which is also linked to the actual post.

&amp;lt;?php
/**
 * Block Name: Featured Business
 *
 * This is the template that displays the featured business block.
 */

 // create id attribute for specific styling
 $id = 'featured-business-' . $block['id'];

 // create align class ("alignwide") from block setting ("wide")
 $align_class = $block['align'] ? 'align' . $block['align'] : '';

 ?&amp;gt;
 &amp;lt;div id="&amp;lt;?php echo $id; ?&amp;gt;" class="testimonial &amp;lt;?php echo $align_class; ?&amp;gt;"&amp;gt;
   &amp;lt;h3&amp;gt;&amp;lt;?php the_field('block_title'); ?&amp;gt;&amp;lt;/h3&amp;gt;
   &amp;lt;?php $post_object = get_field('select_a_business'); ?&amp;gt;
   &amp;lt;?php $featured_img_url = get_the_post_thumbnail_url($post_object-&amp;gt;ID,'full'); ?&amp;gt;

   &amp;lt;p&amp;gt;&amp;lt;a href="&amp;lt;?php echo get_permalink($post_object-&amp;gt;ID); ?&amp;gt;"&amp;gt;&amp;lt;?php echo $post_object-&amp;gt;post_title; ?&amp;gt;&amp;lt;/a&amp;gt;&amp;lt;/p&amp;gt;
   &amp;lt;?php

   if (get_field('display_featured_image') == 'Yes') {
     // code to run if the above is true
     ?&amp;gt;
     &amp;lt;p&amp;gt;&amp;lt;a href="&amp;lt;?php get_permalink( $post_object ); ?&amp;gt;"&amp;gt;&amp;lt;?php echo get_the_post_thumbnail( $post_object, 'thumbnail' ); ?&amp;gt;&amp;lt;/a&amp;gt;&amp;lt;/p&amp;gt;
     &amp;lt;?php
   } 
   ?&amp;gt;

 &amp;lt;/div&amp;gt;

The block looks the same in the editor and on the front end which is very nice. One thing I found is that when I initially add the featured business block and select the business, it did not immediately show up on the back end even though the preview showed the block’s content on the front end. I had to save it as a draft and refresh my browser for the contents of the block to show up in the editor.

ACF does make it very easy to create custom blocks which can be used to build custom templates. Can’t wait to build more custom blocks.

This code is on github if you would like to get it from there. The following sites helped me with building this custom block.

https://www.advancedcustomfields.com/blog/acf-5-8-introducing-acf-blocks-for-gutenberg/

https://www.billerickson.net/building-gutenberg-block-acf/

Verified by MonsterInsights