In the Lab: A Custom Notification Bar Block

Welcome back to the Lab.

For this tutorial we’re going to build a custom notification bar block. Perfect for when you need to drop a notification, notice, or super simple call-to-action on to a page or post.

It’s gonna look something like this:

The custom notification bar block with 3 different styles

Colours and background images will be customisable as well as the text and buttons.

So our local setup for building the block looks like this:

  • Theme: Atomic Blocks Child Theme
  • Plugins: Block Lab

That’s it. Nice and simple. Let’s do this!

First, we plan our block’s fields based on the design. Each field basically corresponds to a unique element in the block. So they are:

Field LabelField TypeField Location
MessageTextEditor
Button TextTextEditor
Button URLURLEditor
ColorColorInspector
Background ImageImageInspector

So in our WordPress Admin and with the Block Lab plugin active, we go to Block Lab > New Block.

Give our new block the title of Notification Bar and configure the block properties. This is what we have:

Custom Block Properties

Now let’s add all our fields as per our table above.

Custom Block Fields

Hit Publish.

You’ll notice that when you hit publish that at the top of the page a prompt appears telling us that our next step is to create a PHP template file and gives us the file name and path for this.

Block Template Prompt

So let’s open up our text editor of choice and create the file. In our child theme, in the top level folder, we’re going to add a new folder called blocks. In this folder we’re going to create a file called (as per the prompt above) block-notification-bar.php.

We’re also going to create a CSS file where we are going to add our CSS code for styling for the block. This file will be named exactly the same as the main PHP file except the file extension will be .css instead of .php. The Block Lab plugin auto-magically pairs these two files together.

With these files saved, we can go back to our Block Editor in WordPress, hit refresh, and we’ll see that our new template file is being picked up now as the prompt has disappeared and now shows the template file path.

Great, so our template file is all set up. Now let’s build it out.

In the PHP template file, let’s stub out our HTML and give the block a CSS class.

<div class="block-notification-bar" >
    <span></span>
    <a></a>
</div>

Next work with the PHP functions that Block Lab gives us for interacting with our custom block and its fields. The primary functions are:

  • block_value()
  • block_field()

block_value stores the data saved to the field. block_field echos the data out. For our block today, we only need to use block_field. So with these functions available to us, our template file looks like:

<div class="block-notification-bar" style="background-image: url('<?php esc_html( block_field( 'background-image' ) ); ?>'); background-color: <?php esc_html( block_field( 'color' ) ); ?>;">
    <span><?php esc_html( block_field( 'message' ) ); ?></span>
    <a style="color: <?php esc_html( block_field( 'color' ) ); ?>;" href="<?php esc_html( block_field( 'button-url' ) ); ?>"><?php esc_html( block_field( 'button-text' ) ); ?></a>
</div>

So what we’re doing here is 2 things. We’re using the block_field function to:

  1. add our content (message, button text, and button url) to their appropriate places in the HTML, and
  2. add inline CSS to handle our dynamic styling

Note that we are also sanitising our function outputs with esc_html. This follows WordPress coding best practices. You can learn more about that here.

For our CSS styling let’s jump over to our CSS template file. The CSS we’re adding looks like this:

.block-notification-bar {
    color: #fff;
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 12px 22px;
    font-size: 16px;
    line-height: 16px;
    box-shadow: inset 0 0 8px rgba(0,0,0,0.2);
    border-radius: 2px;
    font-family: sans-serif;
    background-size: cover;
    margin-bottom: 40px;
}
.block-notification-bar a {
    background-color: rgba(250,250,250,1);
    padding: 10px 12px;
    border-radius: 4px;
    font-size: 12px;
    box-shadow: none;
    text-transform: uppercase;
    letter-spacing: 1px;
    font-weight: 600;
    text-decoration: none;
    line-height: 12px;
}
.block-notification-bar a:hover {
    background-color: rgba(250,250,250,0.9);
}

Our CSS is fairly simple. The trickiest part is that we’re using Flexbox to position our content. Flexbox is new-ish to CSS and if you’ve not checked it out yet, I highly encourage you to.

And that is the final piece of this puzzle. Let’s go create a new Page in WordPress, add our block, fill out the fields and see what it looks like.

In the editor, we can select and add the block to the page:

Adding the Custom Block to the WordPress Editor

Fill in the fields:

The Block Fields in the Editor
The Block Fields in the Inspector

Preview in the editor:

The Custom Block in preview in the Editor

And check it out on the front end:

The Custom Block on the Front End

Sweet!

So to take this even further you could:

  • Conditionally display the button so you can add notifications that don’t require a user action.
  • Add a text color field so you can handle light background colors with better color contrast.
  • Remove the color/background fields and instead handle variations through fixed options with a select field (error, success, message, etc) and some clever conditional CSS classes in the template.

This was nice and easy, but certainly one that could prove to be pretty handy.

If you want to learn more, check out these previous tutorials:

Happy block building!

New Taxonomy Field for Block Lab Pro

Good news today for our Block Lab Pro Early Access Pass holders. You now have access to the Taxonomy field.

The Taxonomy field in the Block Builder

When adding this field to your blocks you can set it to either pull a list of categories or tags.

Selecting Categories or Tags

If you’re building a block that pulls in posts, e.g. a “check out these posts” block, then this field could prove really useful.

This rounds out the Object style fields nicely with the following all now available to Early Access Pass holders:

  • User Field
  • Posts Field
  • Taxonomy Field

Returning the object is now standard for all similar fields types and will be the approach taken moving forward.

Because of the improved UI, the User field is not backward-compatible. Please go to the block UI for every block that has a User field, and click “Update.” There’s no need to change anything on that screen, though.

Also, please select the user again from the user field in the block editor.

Any thoughts, questions, or ideas? Let us know in the comments.

P.s. Stay tuned as we’ll be announcing something pretty cool soon around community.

Backwards Compatability Break for the Image Field

Hi everyone,

If you’re using the image field in Block Lab, you should be aware of a minor backwards compatibility break in the latest plugin update.

The changes are related to when using the block_value() function with the image field. This function now returns an integer attachment ID. Previously it returned the attachment URL.

This breaking change will only occur if:

  1. You are using the image field in a block, and
  2. The template retrieves the image field’s value using the block_value() function or block_field() with the second argument of false, and
  3. The image field has been used in post content with an external URL (not a file hosted in your Media Library).

This change was made as it gives more versatility to what you can do when interacting with the field in your block templates.

The table below gives a good breakdown of how things work moving forward.

Function callExpected resultNotes
block_value( 'foo-valid-url' )returns attachment IDDifferent from before, used to return the URL
block_value( 'foo-invalid-url' )returns 0Also different from before. Returns 0 if the URL isn’t on the same site, or if it doesn’t match an existing attachment (image).
block_field( 'foo-valid-or-invalid-url' )echoes the string URLSimply echoes the string (no change from previous behavior)

When passing a second argument of false to block_field(), like block_field( ‘foo-field’, false), please see the “Function call” documentation above for block_value().

block_field( 'foo-url' ) will have the same result as before, even if it used to have an external URL.

If the URL was previously for an external image, not an image hosted in the Media Library, block_value( 'foo-url' ) will now return 0.

If you have any questions, please don’t hesitate to ask. Additionally, we encourage you to update the plugin on a testing environment or at least have a site backup ready to roll back to should you notice anything broken.

An even better block building experience with v1.2.2

Today we release version 1.2.2 of Block Lab.

This version introduces a bunch of user interface improvements that make it even easier to build blocks within the WordPress admin, particularly for those just getting started with Block Lab.

There are 3 general areas of improvement:

1. Block Properties in Sidebar

The block properties (slug, icon, categories, keywords) are now moved over to the sidebar rather than in the main content column. This simplifies the adding and configuring of fields, which is where you spend most of your time when building a new block.

2. Contextual Prompts

Prompts, “next steps”, and documentation links are displayed when building a new block to help guide you through the process. These only appear at relevant points of the process and disappear once you’ve moved on.

A prompt that includes a template file copy-paste feature. The prompt appears after you hit “Publish” or “Save Draft” and disappears once you create your template file.

3. Add Fields Panel

The “Add fields” panel has some improvements in how it positions rows when adding/moving between them. When you add or select a field row it now positions itself at the top of the panel. This saves you having to scroll to maximise your view of the field settings.

The overall impact of these changes is that the experience of adding, configuring, and publishing a new block is even more streamlined.

Have suggestions for how we can improve the experience even further? Comment on this post or join us over on Github.

In the Lab: A Custom eBook Download Block

Welcome back to the Lab.

For this tutorial we’re going to build a custom eBook download/call-to-action block. It will include a picture of our book, some text, and a button to download the book.

It’s gonna look something like this:

So our local setup for building the block looks like this:

  • Theme: Atomic Blocks Child Theme
  • Plugins: Block Lab

That’s it. Nice and simple. Let’s do this!

Looking at our design above we can figure out the block fields we’re going to need and where we want them to be. Each field basically corresponds to a unique element in the block. So they are:

Field LabelField TypeField Location
Book ImageImageEditor
PretextTextEditor
HeadingTextEditor
TextTextareaEditor
Button TextTextEditor
Button URLURLEditor
Accent ColorColorInspector

Most of these are pretty self-explanatory. The final field Accent Coloris something a little extra. In our design we have that bold blue, but we’re going to make that configurable (apart from the actual image of the book that is). We’re going to let the person adding the block choose an “accent” color that will be used for the button and the little pretext on the right.

So in our WordPress Admin and with the Block Lab plugin active, we go to Block Lab > New Block.

Give our new block a title and configure the basic block settings. This is what we have:

Now let’s add all our fields as per our table above.

Hit Publish.

You’ll notice that when you hit publish that over on the right a notification appears telling us that the plugin is looking for a template file. Currently it’s unable to find it and is letting us know.

So let’s open up our text editor of choice and create the file. In our child theme, in the top level folder, we’re going to add a new folder called blocks. In this folder we’re going to create a file called block-ebook-cta.php. Notice that the notification lets us know what the file needs to be called.

With this file saved we can go back to our Block Editor in WordPress, hit refresh, and we’ll see that our new template file is being picked up now.

Great, so our template file is all set up. Now let’s build it out.

Let’s first stub out our HTML and give the elements CSS classes.

<section class="alignwide block-ebook-cta">
    <div class="block-ebook-cta--wrapper">
        <div>
            <img class="block-ebook-cta--book-image" src="">
        </div>
        <div>
            <span class="block-ebook-cta--pretext"></span>
            <h2 class="block-ebook-cta--heading"></h2>
            <p class="block-ebook-cta--text"></p>
            <a class="block-ebook-cta--button" href=""></a>
        </div>
    </div>
</section>

Next let’s use the two PHP functions that Block Lab gives us for interacting with our custom block and its fields. These functions are:

  • block_value()
  • block_field()

block_value stores the data saved to the field. block_field echos the data out. So with these functions available to us, our template file looks like:

<section class="alignwide block-ebook-cta">
    <div class="block-ebook-cta--wrapper">
        <div>
            <img class="block-ebook-cta--book-image" src="<?php esc_html( block_field( 'book-image' ) ); ?>" alt="">
        </div>
        <div>
            <span class="block-ebook-cta--pretext"><?php esc_html( block_field( 'pretext' ) ); ?></span>
            <h2 class="block-ebook-cta--heading"><?php esc_html( block_field( 'heading' ) ); ?></h2>
            <p class="block-ebook-cta--text"><?php esc_html( block_field( 'text' ) ); ?></p>
            <a class="block-ebook-cta--button" href="<?php esc_html( block_field( 'button-url' ) ); ?>"><?php esc_html( block_field( 'button-text' ) ); ?></a>
        </div>
    </div>
</section>

Note that we are sanitising our function outputs with esc_html. This follows WordPress coding best practices. You can learn more about that here.

We can actually now use this block. If you create a new page or post in WordPress, you’ll be able to add this block. All the fields are there and the saved data is being output. It will look like this in the editor and the frontend:

Before we move on to styling, we’re going to create a variable that can store the accent-color. We can then interact with this variable when styling.

Our variable PHP looks like this:

<?php
$accent_color = block_value( 'accent-color' );
?>

Note that when we added the Accent Color field to the block in the Block Editor, we gave it a default color so that the variable will always have a saved value.

For our CSS styling we’re going use a new feature of Block Lab. In version 1.2.1 we introduced a better way to manage styling. In our blocks folder we’re going to add a CSS file called block-ebook-cta.css. The plugin will auto-magically pair this file with the PHP file of the same name.

So in this CSS file we’re going to add the following:

.block-ebook-cta {
        margin-top: 40px;
        margin-bottom: 40px;
    }
    .block-ebook-cta--wrapper {
        display: grid;
        grid-template-columns: 1fr 1fr;
        grid-gap: 40px;
    }
    .block-ebook-cta--wrapper>div:nth-child(1) {
        background-color: #f4f4f4;
        padding: 80px;
    }
    .block-ebook-cta--wrapper>div:nth-child(2) {
        display: flex;
        align-items: flex-start;
        justify-content: center;
        flex-direction: column;
        max-width: 460px;
        padding: 40px;
    }
    .block-ebook-cta--book-image {
        /* border: 8px solid #fff; */
        max-width: 80%;
        margin: auto;
        /* margin-top: -40px;
        margin-bottom: -80px; */
        box-shadow: 1px 10px 40px 0px rgba(0,0,0,0.28);
    }
    .block-ebook-cta--pretext {
        text-transform: uppercase;
        font-size: 14px;
        line-height: 1em;
        letter-spacing: 1px;
        font-weight: 800;
        margin-bottom: 20px;
    }
    .block-ebook-cta--heading {
        font-weight: 800;
        margin-bottom: 40px;
    }
    .block-ebook-cta--text {
        font-size: 16px;
        margin-left: 20px;
    }
    .block-ebook-cta--button {
        display: inline-block;
        color: #fff;
        padding: 24px 24px;
        text-transform: uppercase;
        font-size: 12px;
        line-height: 1em;
        letter-spacing: 1px;
        font-weight: 800;
        margin-left: 20px;
        box-shadow: 1px 10px 40px 0px rgba(0,0,0,0.28);
    }
    .block-ebook-cta--button:hover {
        box-shadow: 1px 10px 40px 0px rgba(0,0,0,0.4);
        color: #fff;
    }

This gets us 99% of the way. The final piece of CSS is actually going to sit in the PHP template file. The reason for this is that we want it to interact with our stored accent_color variable. So down a the bottom of the block-ebook-cta.php file we’re going to add:

<style>
    .block-ebook-cta--button {
        background-color: <?php echo esc_html( $accent_color ); ?>;
    }
    .block-ebook-cta--pretext {
        color: <?php echo esc_html( $accent_color ); ?>;
    }
 </style>

And that is the final piece of this puzzle. Let’s go create a new Page in WordPress, add our block, fill out the fields and see what it looks like. To change it up, let’s set the accent color to purple.

Nice!

So to take this even further you could:

  • Add other button options. E.g. text color
  • Add CSS to handle the blocks responsiveness for smaller screens

I hope you like this one. I’m pretty happy with how it turned out. 😀

If you want to learn more, check out this previous tutorials:

  • Custom Hero Block
  • Custom Gravity Form Block
  • Custom Pricing Table Block

Happy block building!

New Feature: A better way of handling Block Styling (CSS)

From the first version of Block Lab there have been a couple of ways of handling styling for your custom blocks. You could:

  • Add the styling to the block template file
  • Add the styling to the theme

These were both OK, but there were a couple of weaknesses.

If you added styling to the block template file, that snippet of CSS was loaded for every instance the block was added to the page. For example, if you added 3 custom Testimonial blocks to your page, the CSS would be included 3 times. Not great for performance.

Alternatively, if you added the styles to the theme you didn’t get your styling in the editor. This is because (typically) the theme stylesheet isn’t loaded in the WordPress admin.

Granted there were ways around these issues, but they weren’t a part of the “blocks made easy” ethos of Block Lab.

So we came up with a better solution.

Inside the /blocks folder in your theme, where you keep your block template files, you can now add a block-{block name}.css file.

your-theme/blocks/block-foo.php
your-theme/blocks/block-foo.css

As long as you follow the naming convention, Block Lab automatically recognises that this CSS file is paired with the related template file.

Here’s the really cool part though

  1. The CSS can now be loaded, by the plugin, to the WordPress admin so you get your styling in the editor without having to duplicate code, and
  2. The CSS is CONDITIONALLY loaded, only once, on the front end, and only if the relevant block is on the page

This new feature is a fantastic, yet super simple, solution to making conditional stylesheets accessible to even the most beginner WordPress dev.

We’re really excited about this feature and you can read more about it in the documentation.

Get the latest release of Block Lab from WordPress.org and give it a go.

Block Lab Pro – Early Access

Block Lab Pro is coming mid-2019.

We’re hard at work on it right now. Block Lab Pro is going to take the best of the free plugin (which will continue to get better) and power it up with features that make it the perfect tool for agencies and freelancers. The features we’re building, as well as the premium support, will bring massive efficiencies to site-build workflows around the new WordPress editor.

Today we’re launching the Early Access Pass – A pre-purchase that gives you early access to some of the Pro features as they’re developed in the coming months, as well as locking in a lifetime discount on the annual unlimited site license.

The Early Access Pass includes:

  • A locked-in lifetime saving on the annual license for unlimited sites. $99 instead of $399. That’s 75% off for life.
  • Access to a handful of Pro features that will be made available before Pro release. This includes our Block Import / Export feature which is available right now.
  • A big high-five and thank you from us for being awesome and supporting us as we build and launch Block Lab Pro.

The Early Access Pass is a way for us to accelerate towards the launch of Block Lab Pro. The funds we generate will be reinvested to help ramp-up development and lay the foundation for our premium plugin and service.

Check out the Early Access Pass page for more details including Block Lab Pro features as well as a few FAQ’s around licenses etc.

In The Lab: Building a Custom Form Block with Gravity Forms

One of the first things site builders realise when working with Gutenberg is that the other plugins they use don’t always play as nicely. Many plugins are adding Gutenberg support, which is great, yet the ones that are don’t always give us what we want. Because… well, we want what we want. Not what the average user does. We have unique needs. ❄️

So, in this tutorial, we’re going to show you how you can get what you want.

For this one we’re covering one of the most common needs of a website. Custom forms. There are some great form plugins out there. Free and premium. We’re going to show you how you can use your favourite form plugin and create a custom Gutenberg form block that works with it. Gravity Forms is the plugin of choice for this tutorial but the same process will work with nearly any of the others.

TL;DR. In your block template use the gravity_form() function. In your block add a text field so you can input your form ID.

Let’s do this!

Our block will look like this by the end, but the key thing to learn from this tutorial is how we make the block interact with the form.

The Final Block

Step 1: Creating our Form

For this step we’ll create our form using the Gravity Forms plugin. In our Gravity Forms settings (Forms > Settings), we’re going to turn off the CSS that the plugin outputs to the front end. This means when we write our own CSS it gives us full control over how the form will look.

Now to create our form, in the WordPress Admin go to Forms > Add New.


Call the new form “Contact”.

We’re going to add 3 fields and give each some placeholder text.

Field TypeField NameField Placeholder
TextNameYour Name
TextEmailYour Email
Paragraph TextMessageYour Message

Hit Publish and take note of the Form ID. In this example, the generated ID is 1.


Form = Done!

Step 2: Adding and Configuring the Block

Now we get to building our block.

  1. In the WordPress Admin, got to Block Lab > Add New
  2. Give your new block the title Form
  3. Keep the automatically generated slug.
  4. Choose an icon, set a category, and add some tags.

Step 2 complete. Nice!

Step 3: Adding Fields

Ok, these are the fields we’re going to add:

Field LabelField TypeField Location
Form TitleTextEditor
Form TextTextareaEditor
Form IDTextEditor

As far as fields go, that’s about as simple as it gets.

In the admin, it looks like this:

Add all these fields to your block and hit Publish.

Step 4: Building the Block Template

Time to open a text editor. I use VSCode.

In our Block Building screen in the WP Admin, you’ll see over on the right that the plugin is looking for the block template file for the new block. As we’ve only just added it, it’s telling us it can’t find it. Helpfully it’s also telling us exactly what it’s looking for.

Take note of the name block-form.php and open up your active theme files in your text editor.

Add a folder called blocks.

In this new folder, add a new file and type block-form.php as its file name. Hit save.

Switch back to our block editor in WP Admin and hit refresh just to make sure it’s picking up the new file.

Success!

Now, we build the template. We’re going to write some simple CSS, HTML, and PHP in our template file. There are other ways to do this, including building a preview template file for the block, but for simplicity’s sake we’re going to do it all in this single file.

We’ll have 2 sections in our file. CSS at the top, and HTML and PHP at the bottom.

Let’s stub out the HTML for our block. The structure will include:

  • A div to wrap around our form
  • a h2 for our form title
  • a p for our form text
  • a php tag for where we will call the form function
<div class="block-form">
    <h2 class="block-form_title"></h2>
    <p class="block-form_text"></p>
    <?php 

    ?>
</div>

I’ve also added CSS classes to each HTML element.

Next step is to add the content of our block using Block Lab’s block_field function.

Our block template file now looks like this.

<div class="block-form">
    <h2 class="block-form_title"><?php block_field( 'form-title' ); ?></h2>
    <p class="block-form_text"><?php block_field( 'form-text' ); ?></p>
    <?php 
         
    ?>
</div>

Now we get to the crux of this whole tutorial. We use the gravity_form() function made available to us with the Gravity Forms plugin, alongside our form-id field to output the form in our custom block.

Our code now looks like:

<div class="block-form">
    <h2 class="block-form_title"><?php block_field( 'form-title' ); ?></h2>
    <p class="block-form_text"><?php block_field( 'form-text' ); ?></p>
    <?php 
        $form_id = block_value( 'form-id' );
        gravity_form( $form_id , false, false, false, '', true, 12 ); 
    ?>
</div>

Using the block_value function we can fetch the ID of the form as input by the user when adding the block to a post or page and assign it to the variable $form_id

We then call the gravity_form() function and set a few parameters. For the from ID parameter, we use our $form_id variable.

The rest of the paramaters mean that the title and description will not be displayed, the form itself will not display if it is inactive, and it will not use AJAX for form submission.

To read more about this Gravity Forms function, or embedding forms in general, check out the official docs.

We now have a functioning custom form block that we can to add to a new post or page in WordPress and have it work in both the editor and frontend.

Let’s check it out.

In the WordPress admin, go to Pages > Add New. Now add a new block and look for our “Form” block. Add it to the page and fill in the fields.

In the editor with the block selected.

Click away from the block to view the preview.

In the editor with the block deselected.

And hit the Preview button at the top of the page to preview the form on the front end.

On the frontend.

We now have a fully functional form block.

Time to make it look good! Back in our template file, at the top, we’re going to write our custom CSS. Our styling looks like this:

<style>
    .block-form {
        padding: 60px;
        background-color: #5a3fd6;
        border-radius: 10px;
        box-shadow: 0px 4px 0px 0px rgba(0,0,0,0.5);
        text-align: center;
        color: #fff;
    }
    .block-form_title {
        color: #fff;
    }
    .block-form ul {
        list-style: none;
        margin-left: 0;
        padding-left: 0;
    }
    .block-form input,
    .block-form textarea {
        border-radius: 4px;
        border: none;
    }
    .block-form input[type="submit"] {
        min-width: 30%;
        background-color: #41b8ff;
        box-shadow: 0 3px rgba(38,30,65,.3);
        text-shadow: 1px 1px rgba(38,30,65,.1);
        font-size: 24px;
    }
    .block-form input[type="submit"]:hover {
        box-shadow: 0 10px rgba(38,30,65,.6);
    }
    .block-form label {
        font-size: 0;
        position: absolute;
    }
</style>

With this in the template file, our form on the front end looks like:

Our Final Form

And that’s it! With our styling complete we get a custom Gutenberg block that can display a Gravity form and look just the way we like. ?

So our final template file code is:


<style>
    .block-form {
        padding: 60px;
        background-color: #5a3fd6;
        border-radius: 10px;
        box-shadow: 0px 4px 0px 0px rgba(0,0,0,0.5);
        text-align: center;
        color: #fff;
    }
    .block-form_title {
        color: #fff;
    }
    .block-form ul {
        list-style: none;
        margin-left: 0;
        padding-left: 0;
    }
    .block-form input,
    .block-form textarea {
        border-radius: 4px;
        border: none;
    }
    .block-form input[type="submit"] {
        min-width: 30%;
        background-color: #41b8ff;
        box-shadow: 0 3px rgba(38,30,65,.3);
        text-shadow: 1px 1px rgba(38,30,65,.1);
        font-size: 24px;
    }
    .block-form input[type="submit"]:hover {
        box-shadow: 0 10px rgba(38,30,65,.6);
    }
    .block-form label {
        font-size: 0;
        position: absolute;
    }

</style>
<div class="block-form">
    <h2 class="block-form_title"><?php block_field( 'form-title' ); ?></h2>
    <p class="block-form_text"><?php block_field( 'form-text' ); ?></p>
    <?php 
        $form_id = block_value( 'form-id' );
        gravity_form($form_id , false, false, false, '', true, 12); 
    ?>
</div>

Pretty simple! 🙂

Note that the styling didn’t carry 100% over to the editor screen, even though we had it included in the template file. This was because some styling from the Gravity Forms plugin was given priority in the editor. To get around this we just needed to add some further specificity to our CSS.

I really hope you’ve found this tutorial interesting and helpful. If you have any ideas of what you’d like to see in future ones, please let me know in the comments below.

If you’d like to learn more, check out the previous tutorial on building a custom Hero Block.

Happy block building. ?

In The Lab: Building a Custom Hero Block

Today we kick-off an ongoing series of posts called “In The Lab“. These are going to be fun playground posts where we build cool things with Block Lab. 🙂

For the inaugural post of the series, we’re going to build a custom Hero Block. It’s going to be nice and simple and follow the typical design patterns you expect from the Hero section of a page. There will be a couple of extra controls that let you change the styling of the block, but nothing over-the-top.

To see an example of what this custom block will be able to do, here are 4 examples.

Example Hero Sections built with our Custom Block

So take note of some features of this custom block.

  1. Background Image
  2. Background Colour
  3. Heading & Text
  4. 2 x Buttons
  5. Left, Center, and Right alignment of the block content
  6. Different heading font sizes
  7. Light & Dark text

With this kind of block, it would make it pretty easy to beautify the first section of any of your pages.

So, before we get in to the step-by-step, here is our setup. Fresh WordPress install (v5.03). Block Lab plugin installed and active (v1.1.2). Atomic Blocks child theme installed and active.

We’re using the Atomic Blocks theme for 2 reasons.

  1. It’s great!
  2. It has a great blank “page builder” page template that works as a good blank canvas for working with a Hero kind of block.

Ok, let’s do this! By the end of this tutorial, this is what we will have built.

The Custom Hero Block we are building

Step 1: Adding and Configuring the Block

  1. In the WordPress Admin, got to Block Lab > Add New
  2. Give your new block the title Hero
  3. Keep the automatically generated slug.
  4. Choose an icon, set a category, and add some tags.

Step 1 complete. Nice!

Custom Block Properties

Step 2: Adding Fields

Ok, these are the fields we’re going to add.

Field LabelField TypeField Location
HeadingTextEditor
TextTextareaEditor
Button 1 TextTextEditor
Button 1 URLURLEditor
Button 2 TextTextEditor
Button 2 URLURLEditor
Background ColorColorEditor
Background ImageTextEditor
Background DarkenRangeInspector
Text ColorSelectInspector
Heading SizeRangeInspector
OrientationSelectInspector

In the admin, they will look like this:

Fields for our Custom Hero Block
Admin screenshot of added fields

Take note of the field locations. Rule-of-thumb is that content fields belong in the editor and settings/configuration fields belong in the inspector.

For our background image field, we’re using a Text field. A Media field is coming to the plugin very soon, which would actually be used here. In the meantime, we just paste an image’s URL in to a Text field.

Add all these fields to your block, and hit Publish.

Step 3: Building the Block Template

Time to open a text editor. I use VSCode, but there are plenty you can choose from.

In our Block Building screen in the WP Admin, you’ll see over on the right that the plugin is looking for the block template file for your new block. As we’ve only just added it, it’s telling us it can’t find it. Helpfully it’s also telling us exactly what it’s looking for.

Copy the file name block-hero.php and open up your active child theme files in your text editor.

Add a folder called blocks.

In this new folder, add a new file and paste in block-hero.php as its file name. Hit save.

Switch back to our block editor in WP Admin and hit refresh just to make sure it’s picking up the new file.

Success!

Custom Block Template Notice

Now, we build the template. We’re going to write some simple CSS, HTML, and PHP in our template file. There are other ways to do this, including building a preview template file for the block, but for simplicity’s sake we’re going to do it all in this single file.

We’ll have 2 sections in our file. CSS at the top, and HTML and PHP at the bottom.

Let’s stub out the HTML for our block. The structure will include

  • a section to wrap the whole block
  • a div to use as our background darkening overlay
  • a container div to contain our content within the max content width of the site
  • a wrapper div to position the content of the block
  • and our Hero content
<section class="block-hero">
    <div class="block-hero_background-darken">
        <div class="block-hero_container">
            <div class="block-hero_wrapper">
                <h1 class="block-hero_heading"></h1>
                <p class="block-hero_text"></p>
                <div>
                    <a class="block-hero_button-1"></a>
                    <a class="block-hero_button-2"></a>
                </div>
            </div>
        </div>   
    </div>
</section>

I’ve also added CSS classes to each HTML element.

Next step is to add the content of our block using Block Lab’s available functions. With the block_field and block_value functions we’re going to add our content and base styling fields first and then work with the setting fields (ones we added to the inspector) later.

Our block template file now looks like this.

<section class="block-hero">
    <div class="block-hero_background-darken">
        <div class="block-hero_container">
            <div class="block-hero_wrapper">
                <h1 class="block-hero_heading"><?php block_field( 'heading'); ?></h1>
                <p class="block-hero_text"><?php block_field( 'text'); ?></p>
                <div>
                    <a class="block-hero_button-1" href="<?php block_field( 'button-1-url'); ?>"><?php block_field( 'button-1-text'); ?></a>
                    <a class="block-hero_button-2" href="<?php block_field( 'button-2-url'); ?>"><?php block_field( 'button-2-text'); ?></a>
                </div>
            </div>
        </div>   
    </div>
</section>

By using the block_field function, we echo out the value stored in the database in that particular field.

Let’s take a quick stock-take of what we have. We should now actually be able to add our custom block in a new post or page in WordPress, add in content, and have it work in both the editor and frontend.

So, in the WordPress admin, go to Pages > Add New. Now add a new block and look for our “Hero” block. Add it to the page and fill in the fields.

Custom Hero Block Fields and their Values

Now click away from the block to see the preview in the editor.

Custom Hero Block in the Gutenberg Editor

And then click the preview button to view on the front end.

Custom Hero Block on the frontend

Hey presto. We have a functioning custom block. Now to make it pretty and customisable.

We’re going to add our CSS to the block template itself to keep it simple. Alternate and more DRY ways include adding it to a plugin or a centralised stylesheet.

So our CSS looks like this:

<style>
    .block-hero {
        background-size: cover;
    }
    .block-hero_container {
        max-width: 1080px;
        margin: auto;
        display: flex;
        min-height: 90vh;
        align-items: center;
        justify-content: space-between;
        padding: 40px 20px;
    }
    .block-hero_wrapper { 
        max-width: 600px;
    }
    .block-hero_heading { 
        color: #fff;
    }
    .block-hero_text { 
        color: #fff;
        margin-bottom: 40px;
    }
    .block-hero_button-1,
    .block-hero_button-2 {
        display: inline-block;
        padding: 8px 24px;
        border-radius: 0;
        border: solid #fff 2px;
        background-color: transparent;
        color: #fff;
        font-size: 14px;
        text-transform: uppercase;
        letter-spacing: 1px;
        margin-bottom: 10px
    }
    .block-hero_button-1 {
        margin-right: 10px;
        background-color: #fff;
        color: inherit;
    }
</style>

Our CSS is fairly simple. It’s mostly about giving the Hero section the proper amount of space and alignment on the page. The buttons also get a bit of attention to make sure they actually look like buttons (we’re using anchor tags) and work well against the background images or colour.

Additionally we’re going to add some in-line CSS to section.block-hero to pull in the background image and background color. So that particular line now looks like

<section class="block-hero" style="background-image: url('<?php block_field( 'background-image'); ?>'); background-color: <?php block_field( 'background-color' ) ?>;">

With this styling, we have basically completed the block! With the image added to the background field, this is what we see.

Our Custom Hero Block

This here is looking really good. We could finish right here if we wanted.

However, let’s add some block settings that let the user tweak the block to make it better suit their case-by-case needs.

So the block fields we added earlier that will handle the settings are:

  • background-darken – This lets the user darken the background image to improve contrast with overlaid text
  • heading-size – This lets the user increase the text-size of the heading
  • text-color – This lets the user select between light and dark text based on the image or color they have in the backgroun
  • orientation – This lets the user select between left, right, and center orientations for the block content

We will be writing some basic PHP to handle these. Our code looks like:

<?php
    $background_alpha = block_value( 'background-darken') / 100;
    $heading_size = block_value( 'heading-size') / 10 + 2;
    $orientation = block_value( 'orientation' );
    $text_color = block_value( 'text-color' );

    if ( $text_color == 'dark' ) {
        $font_color = '#272c30';
    } else {
        $font_color = "#fff";

    }
    if ( $orientation == 'left' ) {
        $justify_content = 'flex-start';
    } elseif ( $orientation == 'center' ) {
        $justify_content = 'center';
    } else {
        $justify_content = 'flex-end';
    }
?>

So depending on the values input in to our block in the editor, we are given different values we use within our CSS. Our updated HTML/PHP part of the template now looks like:

<section class="block-hero" style="background-image: url('<?php block_field( 'background-image'); ?>'); background-color: <?php block_field( 'background-color' ) ?>;">
    <div class="block-hero_background-darken" style="background-color: rgba(0,0,0, <?php echo $background_alpha ?>);">
        <div class="block-hero_container" style="justify-content: <?php echo $justify_content; ?>">
            <div class="block-hero_wrapper" style="text-align:<?php echo $orientation; ?>">
                <h1 class="block-hero_heading" style="font-size: <?php echo $heading_size; ?>em; color:<?php echo $font_color; ?>"><?php block_field( 'heading');?></h1>
                <p class="block-hero_text" style="color:<?php echo $font_color; ?>"><?php block_field( 'text'); ?></p>
                <div>
                    <a class="block-hero_button-1" href="<?php block_field( 'button-1-url'); ?>"><?php block_field( 'button-1-text'); ?></a>
                    <a class="block-hero_button-2" style="color:<?php echo $font_color; ?>" href="<?php block_field( 'button-2-url'); ?>"><?php block_field( 'button-2-text'); ?></a>
                </div>
            </div>
        </div>   
    </div>
</section>

With this in place, we can go to our page and edit the block. For our cycling block, we will

  • Darken the background slightly
  • Switch the text colour to light
  • Increase the heading size a bit
  • Set the orientation to center

And now, without further ado. Here is our block.

Our Custom Hero Block with Settings

And with just changing the content and tweaking the settings, you can create more hero sections on any page or post as diverse as these. 🙂

Our final template file, with all our styling and templating looks like:

<style>
    .block-hero {
        background-size: cover;
    }
    .block-hero_container {
        max-width: 1080px;
        margin: auto;
        display: flex;
        min-height: 90vh;
        align-items: center;
        justify-content: space-between;
        padding: 40px 20px;
    }
    .block-hero_wrapper { 
        max-width: 600px;
    }
    .block-hero_heading { 
        color: #fff;
    }
    .block-hero_heading:after { 
        color: #fff;
    }
    .block-hero_text { 
        color: #fff;
        margin-bottom: 40px;
    }
    .block-hero_button-1,
    .block-hero_button-2 {
        display: inline-block;
        background-color: #fff;
        padding: 8px 24px;
        border-radius: 3px;
        color: #333;
        border-radius: 0;
        border: solid #fff 2px;
        background-color: transparent;
        color: #fff;
        font-size: 14px;
        text-transform: uppercase;
        letter-spacing: 1px;
        margin-bottom: 10px
    }
    .block-hero_button-1 {
        margin-right: 10px;
        background-color: #fff;
        color: inherit;
    }
</style>
<?php
    $background_alpha = block_value( 'background-darken') / 100;
    $heading_size = block_value( 'heading-size') / 10 + 2;
    $orientation = block_value( 'orientation' );
    $text_color = block_value( 'text-color' );

    if ( $text_color == 'dark' ) {
        $font_color = '#272c30';
    } else {
        $font_color = "#fff";

    }
    if ( $orientation == 'left' ) {
        $justify_content = 'flex-start';
    } elseif ( $orientation == 'center' ) {
        $justify_content = 'center';
    } else {
        $justify_content = 'flex-end';
    }
?>
<section class="block-hero" style="background-image: url('<?php block_field( 'background-image'); ?>'); background-color: <?php block_field( 'background-color' ) ?>;">
    <div class="block-hero_background-darken" style="background-color: rgba(0,0,0, <?php echo $background_alpha ?>);">
        <div class="block-hero_container" style="justify-content: <?php echo $justify_content; ?>">
            <div class="block-hero_wrapper" style="text-align:<?php echo $orientation; ?>">
                <h1 class="block-hero_heading" style="font-size: <?php echo $heading_size; ?>em; color:<?php echo $font_color; ?>"><?php block_field( 'heading');?></h1>
                <p class="block-hero_text" style="color:<?php echo $font_color; ?>"><?php block_field( 'text'); ?></p>
                <div>
                    <a class="block-hero_button-1" href="<?php block_field( 'button-1-url'); ?>"><?php block_field( 'button-1-text'); ?></a>
                    <a class="block-hero_button-2" style="color:<?php echo $font_color; ?>" href="<?php block_field( 'button-2-url'); ?>"><?php block_field( 'button-2-text'); ?></a>
                </div>
            </div>
        </div>   
    </div>
</section>

I really hope you’ve found this tutorial interesting and helpful. If you have any ideas of what you’d like to see in future ones, please let me know in the comments below.

Happy block building. 🙂

Where it all began

Back in early 2018 I was working on a website and recognised that it was about time I started taking Gutenberg seriously. I needed to move away from the page templates I was using to offer some of the more complex layouts of the site.

Now I’m not an amazing WordPress developer, but … I get by. However, when I went to look at building custom blocks in Gutenberg, I very quickly found myself out of my depth.

I work with some pretty amazing WordPress engineers, a number who have contributed in significant ways to WordPress Core and other projects in the space, so I messaged a couple of them and asked if I could have a bit of dummies intro to building custom blocks. A couple of them, looking into it for the first time, came back and said that they could certainly help but were surprised by how complex it was and that I was going to have to seriously level-up my dev skills. Levelling-up sounded great, but I put it on the shelf for a little while as I didn’t have the time to invest right then.

Fast forward to WordCamp Sydney in July and Luke (co-conspirator here at Block Lab) was giving the keynote presentation and talked the audience through Gutenberg. The talk was great and everyone loved it. During Q&A time at the end, someone piped up and said…

“Wouldn’t it be great if there was an Advanced Custom Fields like solution geared towards building Custom Blocks.”

Bloke in the crowd

Huh… Yeah, that would be great. It would certainly help me personally with my custom block needs. And if I need it, chances are lots of other people would as well.

The next day Luke and I talked it over and decided we were going to build it.

The next day we called our friend Rheinard and asked if he wanted to help out.

The next week we built out a prototype.

With some really really cool feedback from peers and friends in the WordPress community we decided we were going to do a proper good job of this. 2 months on and we released v1.0 of Block Lab to the WordPress plugin repo.

Since then we’ve added new features and received some pretty cool kudos from the community including a mention from Matt Mullenweg in his 2018 State of the Word at WordCamp US in Nashville.

We’ve got some solid plans for Block Lab and are excited about being the solution for all those people like me back in early 2018 who just “wanted a custom block to do X”, but didn’t know where to start.

Save 75% on the Unlimited Sites License

Buy an Early Access Pass for Block Pro and save 75% on the annual license for unlimited sites.

 

Check it out!

You have Successfully Subscribed!