Creating a Block-based Theme Using Block Templates

This post outlines the steps I took to create a block-based theme version of Twenty Twenty. Thanks to Kjell Reigstad for helping develop the theme and write this post.

There’s been a lot of conversation around how theme development changes as Full Site Editing using Gutenberg becomes a reality. Block templates are an experimental feature of Gutenberg (as of 7.2.0), and using them to create block-based themes is in exploratory stages of development. 

A block-based theme is a WordPress theme with templates entirely composed of blocks so that in addition to the post content of the different post types (pages, posts, …), the block editor can also be used to edit all areas of the site: headers, footers, sidebars, etc.

Gutenberg Handbook

Before diving in, I’ll reiterate that much of how this works is subject to change. This spec is in a very early stage. I hope by writing this, your interest is piqued to learn more and contribute your own experiment to the WordPress theme experiments repository.

Step 1: Create the theme project

In its simplest state, a block based-theme’s structure should look something like this:

theme
|__ block-templates
    |__ index.html
|__ block-template-parts
    |__ header.html
    |__ footer.html
|__ functions.php
|__ index.php
|__ style.css

This is refreshingly simpler than most WordPress theme boilerplates. Here’s a quick overview what each file and directory does:

  • block-templates/: page templates that are composed of blocks. These follow the same template hierarchy as traditional themes.
    • index.html: the primary / fallback template to generate a post or page. (Analogous to index.php in traditional theme templates.)
  • block-template-parts/: the common collections of blocks to be used in block templates.
    • header.html: The global header, expressed in Gutenberg-generated HTML.
    • footer.html: The global footer, expressed in Gutenberg-generated HTML.
  • functions.php: This contains the usual theme setup and any other reusable functions.
  • index.php: This is actually just an empty file. You can technically remove it, but it’s a good habit to include an index file in every directory.
  • style.css: Contains your theme’s styles as usual.

Recreating Twenty Twenty as a block-based theme required adding a few extra stylesheets. Overall, I chose to add no extra page templates to keep the demo as understandable as possible.

Step 2: Create the block templates + block template parts

There were just two that needed to be totally rebuilt as blocks: the header and footer. The process for turning these areas into block templates was something along the lines of:

  1. Attempt to create the template parts in the block editor
    • This can be done in a draft post or page. If you’ve enabled the Full Site Editing experiment in the Gutenberg plugin, you’ll see a new admin panel area Appearance/Template Parts — an area where in the future I could create, store, and edit the block template parts in my theme.
  2. Style them as closely as possible using the editor
  3. Add block style variations + additional theme CSS to address any gaps that the core editor
    • Most of these styles were already present somewhere in the Twenty Twenty theme CSS, so I just needed to make minor modifications to assign them to the new blocks.

Step 3: Save those block templates + template parts as distinct files

When Full Site Editing is enabled via the Gutenberg > Experiments panel, Gutenberg will expect that your theme provides block templates, overriding the normal templating behavior:

Once I had my template parts designed and displaying properly, I would switch over to the Code Editor view, copy the markup generated, and paste the code into its respective file within my theme directory’s block-template-parts folder.

Edit: there’s an easier way to do this without switching to the code editor. You can select all blocks (Meta+A), copy (Meta+C), and paste into your text editor.

Step 4: Add theme starter content

In order for the theme to be populated with pages and content, I borrowed the official TwentyTwenty theme starter content. This step wasn’t 100% necessary, but a nice addition to have some content when someone activates the theme on a fresh WordPress site.

Demo

Here is the result: a site running the block-based Twenty Twenty.

Home page of the Twenty Twenty block based theme demo site.

Potential Block Improvements

Converting the header and footer to blocks helped me identify some functionality that would be nice to add to core blocks. Some of these are already in the works.

  • Navigation block
    • Control over how the menu is laid out and collapses in different viewports (#16829)
  • Columns Block
    • The ability control the padding and margins (#10730, #16660)
    • Adjusting the size of one column, the remaining columns don’t resize equally (#19515)

How is this better than what we have now?

The structural block-based theme changes are generally not obvious on the front end. The process of switching between the Code editor, a template file, and previewing the site to achieve the intended design was tedious. However, this is just an interim step before we’re hopefully able to create and edit our theme (and your entire site) via Gutenberg.

WordPress admin screen showing a block template part being edited.

The end benefit will become most apparent when the user can edit every piece of the page individually using Gutenberg. Being able to compose, manage, and reuse parts of your theme all within one visual interface is an exciting idea and one that’s close to reality.

The other exciting aspect of this process was that it required very little PHP — just a few block style variation declarations and standard theme support registration. Everything else is CSS and HTML generated by the editor. To me this feels like a step in the right direction, lowering the barriers to entry for folks that are new to theme development and WordPress.


I invite you to try it out; your comments and feedback are more than welcome. The source code for this theme is available on GitHub:

https://github.com/WordPress/theme-experiments/tree/master/twentytwenty-blocks

In that repository, you’ll find a handful of other block-based theme experiments: converted versions of Twenty Nineteen, the Gutenberg Starter Theme, and a theme called Parisienne. Each contains instructions for installation and activation.

By the way, the theme-experiments repository is open for PRs! I’d love to see more people creating and testing themes that use this method: that’s the only way it’ll grow and improve.

Feel free to ask questions in the comments or in the repository, and thanks for reading!

Music: A Gutenberg-Powered Theme

Announcing the Music theme: an exploration of how Gutenberg can transform theme design and development.

A couple months ago, I created a Sketch document to assist with the design of block-driven themes. I posted about that here on Themeshaper, and provided a couple short examples of how it could be used in a theme design workflow.

Since then, Allan Cole and I have been working to make one of those examples — a site for an imagined band named Superserious — into a working example of a Gutenberg-powered WordPress theme. We named the theme “Music.”

Allan and I set out to experiment, learn, and create a resource for the community. We’ve documented our experience designing and building this theme, and will be publishing our notes in a series of posts here on Themeshaper.

To kick things off, we’re releasing Music on GitHub today. We’d love for you to give it a spin, tinker with it, and explore how it works with Gutenberg. Here are a few things to look out for:


Design

Our design goal for the theme has been to show that it’s possible (and encouraged!) to make a Gutenberg theme that doesn’t necessarily look like Gutenberg. We wanted to create something bold and a little experimental; a theme with somewhat aggressive, non-standard styles.

Gutenberg gives users unprecedented control over their site design, opening the door for variety and experimentation. Our favorite example of this is our cover image blocks. They look great out of the gate, but users can adjust the image, alignment, and color to achieve a wide range of looks:

cover-images.png

 


Development

You’ll be happy to hear that the overall theme development process wasn’t all that different with Gutenberg. Common patterns like headers, footers, and loops work just as you’d expect in a Gutenberg-powered theme.

In many areas, Gutenberg makes things easier for both users and developers. For instance, full-width header images used to require a custom-built customizer or theme option solution, but now they’re essentially built in. This was important to keep in mind while building the theme, and was a very positive change for development.

Creating stylesheets for blocks was pretty straightforward. Expanding on the built-in stylesheets in _s,  we added a blocks.scss file to the SASS directory and placed all of our block-specific styles and overrides there. This kept everything nice and organized and is likely to appear in _s in the future.

Since Gutenberg is output by the_content(), we learned to take special care with any wrapper divs that might clip or obstruct the expected behavior of Gutenberg blocks. We’ll talk more about that in a follow up post.



Block Styles

We’re truly excited about the custom editor styles that ship with Music. These styles are a breakthrough: they give users a much clearer sense of what their visitors will see on the front end.

Best of all (for theme developers at least), the editor styles were a breeze to integrate! We built all of these in over the course of just a few hours.



Like most of the work we do, the Music theme is open source. You can find it on GitHub:

https://github.com/automattic/musictheme/

If you’d just like to see the front end, feel free to click around our demo site here:

https://musictheme.mystagingwebsite.com/

In many ways, designing and building this theme was similar to the way we’ve made themes in the past — but we did carve out a few new practices along the way. Allan and I will be sharing them with you in upcoming posts. In the meantime, we encourage you to download, install, and experiment with Music yourself!

 

Read part two of this series: Designing a Gutenberg-Powered Theme: Music

Designing Themes with Gutenberg Blocks and Sketch

Follow Kjell Reigstad’s process as he explores designing a block-driven theme with Sketch, for the Gutenberg era.

There’s been an exciting discussion happening around the changes that Gutenberg will bring to themes. At Automattic, we’ve begun to prepare for Gutenberg by reevaluating our theme design and development processes.

As part of that work, I did some thinking about how I might start designing a block-driven theme today and what sorts of resources I’d want to have. The most important thing that came to mind was a way to access and customize all of the core Gutenberg blocks with a few clicks. This would allow me to quickly test and iterate on block design without having to dig into code. I do a good deal of my design work in Sketch, so I began to search for a way to make this possible there.

Luckily, there are already a few Gutenberg-related Sketch files in the wild. The Gutenberg Contributors page on GitHub and the Design Principles & Vision page on WordPress.org are great places to start. These are mostly aimed at the Gutenberg editing interface, however, and didn’t quite accomplish what I was looking for, so I ended up building a new file instead:

Gutenberg-Sketch-File.jpg

This new Sketch file contains symbols for all of the default Gutenberg blocks (with the exception of all the embeds, since those aren’t very customizable). With this set of symbols, it’s possible to quickly build a layout composed entirely of Gutenberg blocks using Sketch:

It’s actually pretty fun to use! In a way, it’s Gutenberg — but for Sketch. 😄
From here, it’s easy to start customizing styles:

I took this method for a spin and tried to mock up a theme for an imagined restaurant. To get started, I built out the page structure using default Gutenberg blocks:

From there, I started doing some light customizing. I cut myself off after a while, but the end result looked fairly decent:

I find this pretty cool. It’s an example of what a block-driven theme might look like with just a little bit of CSS customization.

From here, I could easily keep going and put together a complete, modular design system for this theme by customizing the rest of the Gutenberg blocks. I could view the blocks all at once on the Symbols page, and quickly build out a wide variety of layout options to make sure my styles held up to intense layout customization.


I almost ended there, but I decided to confront a lingering concern I’ve had about Gutenberg: I’ve feared that if we lean too much on Gutenberg for theme layout, we’ll end up with lots of very similar, “blocky” themes. The restaurant site I designed above looks fine, but it’s also clearly made of blocks. I wondered if it’d be possible to create something more experimental using this same Sketch file as a base.

So I took another stab at a pretend site design (this time for a band named Superserious), and forced myself to break out of the blocks a little more. Again, I began with a pure-Gutenberg layout:

But this time, I was much more aggressive in my customization and aimed for a more tailored mobile experience with bold typography:

This was a fun exercise, and it helped allay my fears a bit. That first Cover Image has all the usual pieces, but they’re styled in a very opinionated way. The rest of the blocks are fairly standard, but they still stand out because they exist within a heavily stylized, off-balance frame. The overall effect is drastically different from the theme in the previous exercise.


This process was very useful for me, and I’d love to see if it’s useful for the rest of the community as well. You can download and contribute to the Sketch files here:

https://github.com/Automattic/gutenberg-themes-sketch

The repository includes a basic Sketch file with just the symbols, plus all the text hierarchy styles (H1, H2, etc). I also created a library file in case that’s preferable for anyone. We hope to update these files periodically, and would love to hear feedback from others who use them.

In the meantime, we’ll keep experimenting with ways to design themes in this new Gutenberg-based future.

Styling Themes for Gutenberg

What we learned by developing three themes with Gutenberg in mind.

At the Automattic Theme Team meetup in December, we focused on several Gutenberg-related projects. The first one we’re sharing is a set of Gutenberg-friendly themes based on Underscores.

The project’s goal was to help us think about our themes differently, dig into adding theme support for Gutenberg, and as a byproduct, do some testing of Gutenberg itself.

Six team members participated in this project, and it resulted in three themes which are still in progress, and currently available on GitHub.

What is Gutenberg?

Gutenberg is the new block-based content editor currently being developed in GitHub for WordPress 5.0. Until it’s merged into core, it’s available as a plugin.

It’s really going to change the WordPress publishing experience! From the WordPress.org Gutenberg page:

The Gutenberg editor uses blocks to create all types of content, replacing a half-dozen inconsistent ways of customizing WordPress, bringing it in line with modern coding standards, and aligning with open web initiatives. These content blocks transform how users, developers, and hosts interact with WordPress to make building rich web content easier and more intuitive, democratizing publishing — and work — for everyone, regardless of technical ability.

The Themes

The three themes we developed during the meetup are called Fashion Blog, Handicraft, and Ohana. We decided to try to make these themes CSS-only to help keep the focus on Gutenberg itself and let us build on the recent work the team’s been doing with Style Packs. This turned out to be an ambitious restriction — a little more on that later — but it made for an interesting design challenge.

Fashion Blog, Handicraft and Ohana are currently available on GitHub; you can learn more about each theme there and check out exactly how they were set up. The themes are still works in progress and have some rough edges. The end goal is to get them ready for WordPress.com.

The Process

Over the course of a few days, we researched and decided on an audience for each theme, designed and built them, and added Gutenberg support.

We opted to use a one-column design for all three themes, to best accommodate the “full” and “wide” block alignment options in Gutenberg.

Though it can vary from theme to theme, this is how Handicraft styles Gutenberg’s wide alignment (on the left) and Fashion Blog styles the full alignment (on the right).

Adding Gutenberg Support

You don’t actually have to do anything to use Gutenberg with a theme, but by declaring theme support you can add two optional features: the “wide” alignments (full width and wide width), and custom colors for the block-color palettes.

The following example, when included in the setup function in functions.php, will add both:

/**
* Add support for Gutenberg.
*
* @link https://wordpress.org/gutenberg/handbook/reference/theme-support/
*/
add_theme_support( 'gutenberg', array(

    // Theme supports wide images, galleries and videos.
    'wide-images' => true,

    // Make specific theme colors available in the editor.
    'colors' => array(
        '#ffffff',
        '#000000',
        '#cccccc',
    ),

) );

Whether or not you include custom colors in your theme, Gutenberg will always include a color picker with the palette, for further customization.

Gutenberg’s default color palette, shown while editing the Button block.

Styling the Themes

In general, the default blocks don’t need styling — Gutenberg already includes styles that match each block’s functionality. For example, the Gallery block already has the styles needed to split your galleries into different columns, and the Cover Image block will place the text and image added on top of each other, without the theme’s help.

If any of the styles don’t fully suit your theme’s design, you can adjust them as needed. One thing we noticed while we were developing these themes was Gutenberg’s distinct pill-shaped button style, which might not work with every theme.

On the flip side, themes are fully responsible for figuring out how the “wide” and “full” alignment styles should be handled, if they support them. This makes sense, since support is optional, and exactly how they should look can vary depending on a theme’s individual style.

At the time of writing, the Gutenberg theme styles these two alignments by setting max-widths for specific HTML elements, with a wider max width when either the .widealign or .fullalign classes are used.

In our three themes, we approached it a bit differently, setting a max-width for the page content, and instead using CSS to stretch those wider elements outside of it. We used vw and stretched the wider elements based on the screen size:

@media (min-width: 750px) {

    .alignfull {
        margin-left: calc(50% - 50vw);
        margin-right: calc(50% - 50vw);
        width: auto;
        max-width: 1000%;
    }

    .alignwide {
        margin-left: calc(25% - 25vw);
        margin-right: calc(25% - 25vw);
        width: auto;
        max-width: 1000%;
    }

}

This approach works, but because vw includes the width of the vertical scrollbar as part of the whole screen width, you can get a little horizontal scrolling. One fix is adding overflow: hidden to one of the page-width elements further up the HTML tree.

If you didn’t want these elements’ widths to be based on screen size, you could also set a specific max-width. There’s no one “right” way to approach these styles, and I’m sure more and more examples will come out of the woodwork as more themes add styles for Gutenberg. For example, Justin Tadlock has shared his method using different calc values, and Joen Asmussen has blogged about his approach of applying max-widths to all child elements that aren’t wide or full width.

In our themes, we also kept any block-specific styles separate in their own stylesheet.

Adding Editor Styles

To make the editing experience more what-you-see-is-what-you-get, you can add Gutenberg editor styles using enqueue_block_editor_assets. It’s similar to how editor styles can be enqueued for the current TinyMCE editor. This makes sure what a user sees when building their pages best matches how the content will actually look with your theme when published.

Here’s an example of enqueuing an editor-specific stylesheet:

/**
* Enqueue editor styles for Gutenberg
*/

function theme_slug_editor_styles() {
    wp_enqueue_style( 'theme-slug-editor-style', get_template_directory_uri() . '/assets/stylesheets/editor-style.css' );
}
add_action( 'enqueue_block_editor_assets', 'theme_slug_editor_styles' );

Like with the TinyMCE editor, you can also include fonts. So for example, if your theme is enqueuing fonts from Google, you can include them in the Gutenberg editor, too:

/**
* Enqueue editor styles for Gutenberg
*/

function theme_slug_editor_styles() {
    wp_enqueue_style( 'theme-slug-editor-style', get_template_directory_uri() . '/assets/stylesheets/editor-style.css' );
    wp_enqueue_style( 'theme-slug-fonts', theme_slug_fonts_url(), array(), null );
}
add_action( 'enqueue_block_editor_assets', 'theme_slug_editor_styles' );

Unlike the TinyMCE editor, Gutenberg’s editor styles include the post title:

An example of Ohana’s editor styles.

The editor styles need to be pretty specific to make sure they’re not applied to other elements of the page outside of the editor — Rich Tabor has a good post here about his experience with this behavior. Gutenberg includes specific classes around different elements in the editor, so you can prefix selectors more generally with the class .editor-post-visual-editor, or use more specific classes to target individual blocks — for example, styles for .editor-block-list__block[data-type="core/heading"] h1 would only be applied to h1s inside of a Heading block.

What We Learned

Overall, this project was a great way to ramp up quickly on some Gutenberg-theming basics, and get our feet wet. Some specific things we learned from this process include:

  • The Gutenberg default block styles are numerous and can be a bit opinionated. This is good, in that you can rely on Gutenberg to do a lot of the heavy lifting, but there are some styles that would need to be updated to match individual theme styles.
  • It can be tricky to set up the wide and full-width styles; as more themes add styles for Gutenberg, it’ll be interesting to see all the different ways themes handle this.
  • Setting up the block styles for the back-end editing experience was more involved than any of us had anticipated. It’s very much like adding editor styles to the current TinyMCE editor, but some Gutenberg blocks have very specific classes that needed to be overridden.

We also learned a couple non-Gutenberg related things:

  • From a project-planning perspective, we could have spent more time narrowing down the kinds of themes we wanted to build — and the actual designs — prior to the meetup. This would have left more time to focus on the Gutenberg part of each theme.
  • In the end, it wasn’t possible to complete the project without making edits to these themes in addition to CSS. On top of the PHP changes needed to support Gutenberg’s optional features, we needed to make edits for common WordPress.com-functionality — like adding social menus, and more Content Options support — and for the designs themselves, like enqueuing Google fonts.

Next Steps

Our goal is to get these themes launched on WordPress.com. To get there, they still need some WordPress.com-specific functionality, like the annotations for WordPress.com’s custom fonts and colors, WooCommerce support, and styles for WordPress.com widgets.

We hope that sharing this process is helpful for your own Gutenberg journey as themers. We’d love to hear about your adventures.

 

The Future of Underscores and A New Committer

The title may strike you as a bit ominous, but fear not. Underscores, our popular starter theme for WordPress theme development, isn’t going anywhere. As we continue to push for consistency in themes and imagine what they might become with Gutenberg, we’re bringing our attention back to Underscores. 🚀

For the last year and a half, we’ve experimented with a new starter-theme generator called Components. It was a way to make a few different theme “types” comprised of different components. The starter themes born from it brought with them more code and styles, and gave theme authors a bigger head start in their work. The generator we built to piece the different components together got complex quickly, though. We created a plugin to test builds locally and struggled with a seamless way to make many starter themes from one code base.

We learned a lot, though. We worked on Components at two team meetups, made almost 900 commits to the project and launched dozens of themes with it. However, we hit a point where we realized we had over-engineered parts of the project. The original idea is still solid: make starter themes do more by crafting them out of building blocks. But we didn’t hit the mark, so we’re retiring Components, and looking to bring some of what we learned there to Underscores.

In the last year, we’ve gotten a lot of questions from the community about Underscores and whether we had abandoned it. No way! It’s a stable project, and we enjoyed working on something new, away from it. It gave us better perspective and more ideas for the future of Underscores.

We also know that involvement from the community is vital. It’s been a while since we added our first contributor external to Automattic. To that end, we’ve given long-time Underscores contributor Ulrich Pogson commit access. He’s also a contributor to WordPress, most frequently as a member of the Theme Review Team. We’re excited to have his expertise and passion for world-class themes as part of the project. Please join me in welcoming Ulrich! 🎉

It’s always hard to let go of a project, in this case, Components. But it shouldn’t be, when you walk away with more knowledge than before. It has us excited and reinvigorated about Underscores and its role in the future of theming. And we’re glad Ulrich will help us along the way!

Content Options in Jetpack 4.5

Now available through Jetpack, Content Options let users make small visual changes, like showing or hiding the author, date, featured images, and more.

Last August, we introduced a new WordPress.com Customizer panel called Content Options, which gives users an easy way to make small visual modifications across their sites – no custom CSS needed.

Content Options supports four main features: Blog Display, Author Bio, Post Details, and Featured Images.

Content Options are now available to self-hosted WordPress sites with the latest version of Jetpack (4.5). Theme developers can add support for Content Options by following the Jetpack guide.

Let’s look at the main features of Content Options in more detail.

Blog Display

Users can choose between displaying the full content of each post or an excerpt on the blog and category, tag, and date archive pages, as well as search results.

Full post blog display option in Shoreditch
Full post blog display option in Shoreditch

Post excerpt blog display option in Shoreditch
Post excerpt blog display option in Shoreditch

Default Blog Display

If a theme displays either an excerpt or the full post depending on the post’s post format, theme developers can add a “Default” blog display option to let the theme keep its default blog display settings. For example, by default a theme might always displays posts with the Quote post format as the full post, so a quote is never truncated, while other post formats like Standard might be always displayed as an excerpt.

Default blog display option in Button
Default blog display option in Button

Author Bio

On the single post view, users can opt to display the name and bio of the post’s author. This information comes directly from the author’s profile at Users  Your Profile, and their Gravatar image.

Author Bio displayed on single post in Shoreditch
Author bio displayed on single post in Shoreditch

Post Details

The post details section allows users to show or hide the post date, categories, tags, or the post author’s name.

Post Details displayed in Penscratch
Post details displayed in Penscratch

Post Details hidden in Penscratch
Post details hidden in Penscratch

Users can choose whether to display featured images on single posts and pages. They can also opt whether to display featured images on blog and archive pages, which include category, tag, and date archives as well as search-results pages.

Featured Images displayed in Sela
Featured images displayed in Sela

WordPress.com users have loved the flexibility Content Options gives them. We’re very pleased that self-hosted sites can now benefit as well!

Restricting User Content: A Dialogue Among Themers

I had a Slack chat with my colleagues recently that we thought might be of interest to other themers.


Ernesto: I have a small theming question I’d like to clarify. Let’s say I have a page that is used as front page and there’s a section in the front page that displays some text. I can display the page’s content there, using the_content(), but I would only want there to be text — no fancy shortcodes or custom content, just basic formatting.

Would you create your own content filter for that section? Something like adding wpautop, convert_smileys, and wp_kses_post (possibly others too, if they make sense) into that filter? Or just use the_content() ?

I am leaning towards the filter approach, since it may give me what I want, without giving users full liberty to put all sorts of things into a div that is supposed to hold some minor text and content.

Tammie: This feels like a UX issue too. Why are you restricting?

Ernesto: Because it’s not a full content post, it’s a space where there should be one or two paragraphs at most. Just some introductory text.

theme screenshot

Tammie: Then why let full content appear anyway? Post restricting is expected behaviour, page restricting isn’t. Let’s not add a new behaviour.

I’d say the_content() and if user messes up, well…

If you limit that it’s adding a new behaviour.

Ernesto: Yeah, that makes sense.

Caroline: I’d agree with keeping it as simple as possible.

Tammie: Maybe they want to add a link. Adding a link there is a totally expected thing.

Caroline: So, the_content() works 🙂 And then with [the new content settings feature we’re working on] they could change it to the_excerpt() someday soon.

content-settings

Tammie: Yep, win win.

Ernesto: Very good point… I see no problem with using the_content(), but since I know users want to add everything + the kitchen sink, I was just trying to avoid that.

Caroline: Hahaha.

Ernesto: So yeah, win win.

Tammie: Well that’s assuming they do. Many don’t.

Technically the ones that do make up for ones that don’t😉

David: Yeah, the_content() all the way.

Kathryn: Agreed 100%.

Ernesto: It’s interesting knowing your thoughts on this😀

David: If they put too much content in there, make the theme break elegantly.

Kathryn: If user wants to make their site busy, let them do it.

Kathryn: Users shouldn’t put a zillion widgets in one widget area, but we let them do that😉

Ernesto: Hehe, let them break and then tell them well… you shouldn’t do that.

David: It’s our job as developers to make themes that just work. Part of that is making edge cases not blow up a theme.

Tammie: Well, there’s hand holding and there is spoon feeding. Hands > spoons.

Kathryn: Very much agree re: “Part of that is making edge cases not blow up a theme.”

Also, making cluttered/ugly is different than “breaking”.

Ernesto: I think this is a very good & mature way of thinking… adding stuff for edge cases just makes the theme bloated.

Tammie: Also, edge cases aren’t always bad. We tend to have edge PTSD.

Kathryn: And there’s so much in between cluttered and minimal that is going to look just fine, I think.

Tammie: Yep.

Ernesto: Right, very good discussion and input, thank you so much, that’s why I love y’all:-)

Tammie: Also I kind of love the fact you didn’t even suggest a theme option for that.

Kathryn: Ha.

Ernesto: Hahaha.

Tammie: Times have changed and I like them.

Ernesto: I was going to admit it crossed my mind, but then noticed a page would be cleaner.

Tammie: And that’s why I have even more love about it. Self correcting rocks.

Ernesto: “If they put too much content in there, make the theme break elegantly.” – David Kennedy: Seriously?

David: Yep, I think that’s a sign of theme greatness.

Ernesto: That’s right, the I did what I could to hold the user’s content attitude, I like that too. Definitely adding some float-clearing there.

David: Before this, I worked at a place with a giant, talented editorial team. I thought, Perfect, we can work with them to get exactly the content we need! But they found ways to break things all the time. So whether you know the content, or don’t know it, make it highly fault tolerant.

Ernesto: Very very good advice, thank you!

Show the Latest Featured Image from Featured Content

For the latest ThemeShaper remake, we added Featured Content to Twenty Sixteen. That’s standard, but our design called for not showing the featured image of every post, but only the latest post. That image serves as a backdrop to our collection of featured posts, which can be from one to three posts at a time. It’s a neat design pattern, so I thought I’d share the code needed to grab that image.

First, I assume you have featured content set up like the example code from the Jetpack documentation suggests. Next, let’s write a function to grab that image:

function mytheme_get_first_featured_featured_image() {
	$featured_posts = mytheme_get_featured_posts();
	if ( is_array( $featured_posts ) && ! empty( $featured_posts ) ) {
		$post_id = (int) $featured_posts[0]->ID;
		if ( has_post_thumbnail( $post_id ) ) {
			 $big_post_image = wp_get_attachment_image_src( get_post_thumbnail_id( $post_id ), 'mytheme-custom-image-size' );
			 printf( 'style="background-image: url(%s);"', esc_url( $big_post_image[0] ) );
		}
	}
}

Using it in your theme:

<div id="featured" class="featured-posts" <?php mytheme_get_first_featured_featured_image(); ?>>

<!-- Other stuff -->

</div>

A few notes about what’s happening in the code above:

  • First, we need to grab the featured posts, and check to make sure there are some posts.
  • If there is, we assign the post ID of the latest post to a variable, $post_id. We’ll need that later.
  • Next, if the latest post has a post thumbnail, we create another variable, $big_post_image, and use it to assign the actual output of the image URL.
  • Finally, we output the markup. It outputs as a style attribute, and you can then style the rest via CSS. In your theme, you just attach the function to the div or html element you want to apply the style on.

That’s it! Hopefully, this code snippet helps you in the next theme you create. Happy theming!

Jetpack Social Menu

With the release of Jetpack 3.9 last month, we introduced a new tool available for all theme developers: Social Menus. It allows site owners to create a new menu location which is used to display links to Social Media Profiles.

Adding Support

Theme developers can add support for a Social Menu by following these three simple steps.

Step 1: Declare support in a function hooked to after_setup_theme.

add_theme_support( 'jetpack-social-menu' );

Step 2: Create a new function to avoid fatal errors if Jetpack isn’t activated.

function themename_social_menu() {
	if ( ! function_exists( 'jetpack_social_menu' ) ) {
		return;
	} else {
		jetpack_social_menu();
	}
}

Step 3: Use the function created in step 2 to output the menu where you would like it displayed in the theme.

themename_social_menu();

Styling

Once you’ve created a menu, Jetpack will automatically enqueue a basic stylesheet to style each one of the menu items, thanks to Genericons. You don’t have to do anything else!

Introducing Components: A Toolbox for WordPress Theme Development

Meet Components, a starter-theme generator to speed up WordPress theme development.

We love a good starter theme. Since launching Toolbox and its popular successor, Underscores, we’ve always reached for a starter theme when building our next, awesome WordPress theme to get us off on the right foot. With Underscores, we always say it gives you a 1,000-hour start. We get excited when we see someone fork Underscores and make it their own, so it shouldn’t come as a surprise that we’re obsessed with evolving what we think of as a starter theme.

Continuing that journey, we’re pleased to announce Components. Think of it as a toolbox for taking your themes where you want them to go, faster. Forked from Underscores, Components gives you a solid base to work from – but it also takes the starter theme to the next level, offering a choice between five different theme types. Each one adds the code needed for starting a certain type of theme. You can select from:

The Classic Blog

  • A two-column layout
  • A sidebar with widgets
  • Navigation in the header
  • A fixed maximum width of 1120px in your style.css file

The Modern Blog

  • A single-column layout
  • A sliding panel for navigation, social menu, and also widgets
  • A large featured image with full-width script

Portfolio

  • A portfolio post type, courtesy of Jetpack, added to all the necessary files
  • A grid portfolio view
  • A single column blog template
  • A sliding panel for navigation, social menu, and also widgets
  • A large featured image with full-width script

Magazine

  • A front page template with featured images in grid a layout, plus a two-column blog
  • Layout with excerpts
  • A two-column layout
  • A sidebar with widgets
  • Navigation in the header
  • A fixed maximum width of 1120px in your style.css file

Business

  • A front-page template with a custom header, testimonials section, and  page content area
  • A custom testimonial post type turned on, courtesy of Jetpack
  • A two-column layout
  • A sidebar with widgets
  • Navigation in the header
  • A fixed maximum width of 1120px in your style.css file

Why Components?

So why the different approach with Components? Three main things inspired this direction: the community behind Underscores, the people who use our themes every day, and the web design and development community.

While maintaining and improving Underscores, we always see great pull requests from the community that we turn away because the contributions end up being too specific for a normal starter theme. Many of those additions would have been perfect in most themes. Now, some of them have a home in a project that zeroes in on a certain kind of user with each theme it builds. Speaking of users, we know from launching hundreds of themes on WordPress.com that themes are one of the most challenging areas of WordPress for people to understand. They need more themes that “just work,” and we hope Components will help achieve that. Lastly, the web community has embraced building systems, methodically created with the pieces that make up a site. Even some popular libraries have taken this approach. We see Components as the first step to allowing you to make a starter theme that’s just right for your project.

We’re very excited to see what the community brings to the project and are looking forward to evolving Components with your help. Right now, we’re in the early stages of our vision and execution for Components, so expect both repositories that power this project, theme-components and components.underscores.me to evolve quickly and constantly.

Fork or download Components on GitHub or generate your own custom starter theme at components.underscores.me and have fun making awesome new WordPress themes!

Give Your Jetpack Themes a Boost

If you’re making themes, Jetpack allows you to easily add additional functionality to your themes in a consistent way without a lot of overhead — and without accidentally wandering into “plugin territory.” Here at Automattic, more and more of our themes take advantage of Jetpack to implement site logos, featured content sliders, testimonials, portfolios, food menus, and other special functionality.

The trouble is that users don’t always realize they need to activate Jetpack in order to turn on this functionality. With so many installing themes directly from their WordPress dashboards, most users don’t even know where to find a readme file. As a result, we saw tons of confused users posting in the WordPress.org forums, asking how to make their sites look like our demos.

What we needed was a way to easily inform our users that their theme relied on certain Jetpack modules, and help them install or activate them as needed. This would save on support time as well as make our users happy. We also needed a solution that would be easy to add to lots of different themes, without requiring a lot of manual labor.

Enter the Jetpack Dependency Script

We’ve been working on a solution to this problem over the past few months, and we’ve come up with a simple script that helps our users figure out what’s going on. Since starting to use it in our themes, we’ve seen the number of support requests drop substantially.

Since we love open source, we’ve made the code freely available on Github — so you can use it, too!

Give It a Spin

Want to start using it in your themes? Download it from our Github repo, put it somewhere in your theme — I recommend the inc folder — and include it from your theme’s functions.php, like so:

/**
 * Load plugin enhancement file to display admin notices.
 */
require get_template_directory() . '/inc/plugin-enhancements.php';

You’ll want to replace all instances of textdomain in the script with your theme’s text domain, since it adds a few new strings. You’ll also want to regenerate your theme’s POT file once that’s done.

How It Works

Here’s how it works in Sela, which uses a Site Logo and the Testimonials custom post type.

If the user doesn’t have Jetpack installed, they’ll see this:
Install Jetpack

If the user has installed Jetpack, but hasn’t yet activated it:
Activate Jetpack

If the user has installed and activated Jetpack, but hasn’t activated the required modules:
Activate Custom Content Types module

The notifications appear on the user’s dashboard and on the Themes and Plugin pages. The notifications can be dismissed so they don’t annoy users who don’t want to use Jetpack.

What’s Under the Hood?

Since the script is looking for theme support using current_theme_supports(), themes need to explicitly register support for the Jetpack features they support. Some Jetpack features — like testimonials and portfolios — are available across all themes, and don’t require the theme to explicitly declare support for the feature. Be sure to add theme support for all Jetpack features you intend your theme to make use of. You can declare support like so:

add_theme_support( 'jetpack-portfolio' );

The script checks for theme support first, then checks to see if the required plugins (Jetpack) and modules are activated. It then builds out notifications tailored to the user’s individual situation, so that users are effectively guided through the process of installing and activating the plugin.

Blast Off!

Presto! In only 366 lines of code, we have happier support people and happier users. Feel free to use this script in your own themes, or remix it for your own purposes.

Challenges in JavaScript-Based Theming

Welcome to part three of our tutorial on building themes with JavaScript. In part one we considered the JavaScript web landscape and where it leaves us today. In part two we looked at the forthcoming WordPress REST API. In part three, we will consider the most pertinent question: how do we apply all this to WordPress theming? Some of you are likely already realizing that there are surely a lot of challenges in doing so. And you would be right.

Watch the video presentation or read the transcript below.

Demo Materials

You’ll find accompanying material for this screencast available in a public GitHub repo — each screencast has a corresponding folder with a very simple theme that can be activated.

Getting Real

As you may have noticed in the previous tutorial’s files, we need a theme skeleton to make a project like this work. Fortunately, WordPress only requires themes to have a style.css and index.php file to be recognized. Beyond these two files, we can build the whole thing in JavaScript. If this thought is setting off alarm bells for you right now, I understand. Put those alarm bells to one side for just a little while.

If we are going to build a theme with JavaScript, we probably don’t just want one massive JavaScript file. We also don’t want to have to enqueue lots of separate JavaScript files just for the sake of keeping things tidy. Fortunately, others have already done this work for us. CommonJS — a project which, like Node.js, kicked off in 2009 — has created a myriad of specifications and conventions for JavaScript developers to follow; they’re a bit like a JavaScript version of the W3C. The CommonJS project has created specifications for JavaScript modules, which we can use to split up our code. JavaScript modules allow us to create something similar to a WordPress theme, with different JavaScript files containing different template parts and theme files.

Although we can split out our code into different JavaScript files as we can with PHP, unlike with PHP, we’ll want to concatenate these files into one when we run the theme. In theory, we don’t have to do this — but if we don’t, each page would need to enqueue lots of different JavaScript files, which is bad for performance and user experience.

To concatenate the files we’ll will need to use a build tool, such as CodeKit, Grunt, or Gulp. We can even use Unix’s Make utility, which was first released in 1977(!), to run our build process. At this stage, it doesn’t really matter, as the main thing our build process will do is smoosh our JavaScript files into one file, so whichever utility you’re most comfortable with is fine. For this tutorial, I’ll use my current favourite, Webpack.

Let’s take a look at how these JavaScript modules work. In part two, I showed an example of a very basic JavaScript theme with some inline JavaScript. We were breaking quite a few WordPress conventions, with everything in one big index.php file.

I’ve now broken this up and turned it into a more conventional theme. In index.php we now just get a header and footer. We’re now enqueueing our JavaScript in our functions.php file correctly. And our JavaScript file now sits on its own.

But if you look closely, you might notice something has changed. Our changePost function has disappeared, and instead we are requiring the changePost function. If we go back to the containing directory, you can see that we also have a changepost.js file. This file now contains the changePost function. Note that at the bottom, we have a line that says module.exports = changePost. This is the CommonJS convention for defining what the module actually is. So when we require it, this ensures that what we require is the changePost function itself.

Let’s get concatenating. I’ve mentioned that we’re using Webpack, so let’s get that set up. First, you need to install Node.js. Fortunately, this is a lot easier than it used to be — simply go to nodejs.org and download the automatic installer for your system. Once node.js is installed, we can run a command to install Webpack:

npm install webpack -g

This gives us global command-line access to Webpack. With this done, we can now run the most basic Webpack command, which is to take a source file, and smoosh it into a compiled file. The command for this is:

webpack ./theme.js compiled.js

We can now view the compiled file and see that it contains the contents of both changepost.js and theme.js. An extra little bonus with Webpack is the -p flag, which simply means that you want to minify the file – remove whitespace and remove all comments etc. You can see that even this simple example our compiled file is almost a third of the size it was unminified.

We can also add the -w flag which means we want Webpack to watch the files and automatically recompile whenever we change anything.

With the file compiled, we can see everything in action working together.

The Route of All Evil

With everything we’ve looked at so far, you can probably imagine stringing together a theme that allows a user to browse through different chunks of content from their website. However, a major missing piece is routing, something that you may not have heard of. Routing broadly encompasses the way that we deal with URLs changing. Let’s say a user visits our site, clicks to a different post and wants to share the link. With the examples we’ve looked at so far, this isn’t possible. Routing also ties into our user’s history. If we have no routes, the user can’t press the back button. No routing also means we have little chance of anything meaningful being indexed by search engines. I’m sure you can now appreciate that routing is very important.

In PHP, WordPress deals with this for us. There is a rather large class called WP_Rewrite (you can find it in wp-includes/rewrite.php). This handles every different type of URL and works out what should be shown to the user. In JavaScript, we don’t have this luxury, so we have to deal with it ourselves.

Let’s look at something basic we can implement.

If you look closely at changepost.js, you’ll notice that I’ve added a new line since the last tutorial. As well as editing the document on success, I’ve added a line that redefines window.location.hash. This is the most basic way of changing our user’s route. You’ve probably seen this used on other websites and it amounts to the same thing as using an anchor link to take the user to certain heading on a page.

Let’s look at this in action. Our eventListener has been added to the first link in the menu. If we click it, note that the route now changes.

So with some very basic routing, we now want to change what happens if the user clicks back.

If we go back to theme.js, the eagle-eyed among you may have noticed another line beneath my link listener:

window.onhashchange = changeRoute

We’re hooking a new function, changeRoute, onto window.onhashchange. Every time the URL changes, the browser fires a hashchange event, so this method allows us to tag our own JavaScript on to what happens when the hash changes. You can see beneath this I have a changeRoute function. Here, we say if the hash equals nothing — as in, we’re on the homepage — show the original post that we fetched in the first place. The code here is almost identical to changePost, but it just gets the original post.

What About no-js?

A few minutes back I mentioned that you might have alarm bells ringing. We’ve now likely dealt with a couple of those alarm bells. But we’re not done. Some of you may be thinking, “But what if the user doesn’t have JavaScript enabled? Or what if something has caused JavaScript to break?” In our current scenario, our website simply wouldn’t work.

There are some who don’t think this is a problem. Today, only a tiny number of people browse the web with JavaScript turned off, and for the most part they’re probably power users who fully understand why they have it turned off and know that it will limit their experience. But I am personally not convinced that we should just forget about no-js situations.

Will Somebody Please Think About the Search Engines?!

Even if we sort out our routing, what about search engines? As it happens, Google is now able to render JavaScript. I’m not sure if it’s official yet, but I’ve experimented with this. For example, the ThemeConf website has no server-side rendering, but try Googling “ThemeConf”. It also works on DuckDuckGo. Despite this, it’s not a great idea to rely on others to render your JavaScript — there are also places where this doesn’t work. Ironically, even though Facebook developed React, it doesn’t render JavaScript-rendered content when you’re embedding a link, for example. To see this in action, and if you use Facebook, try pasting a link to ThemeConf.com there. You don’t have to actually share it of course, but you should notice that the preview of the content Facebook will embed is blank.

I believe the most compelling reason to not rely on JavaScript rendering is performance. A developer at Google called Jake Archibald has given some great talks on this. In a worst-case scenario, our current theme makes our users wait for three page loads when they first arrive. First, the page loads, then the JavaScript loads, then the JavaScript loads the content from the REST API. Yuck! This may not be a problem if you’re connected with fiber-optic broadband, but if you’re on a mobile device or a spotty Wifi connection, you’ll really feel the pain.

This ties back into the search engine point, since we know that Google does take page-load times into account when ranking sites in search results. We really don’t want our load times to be three to four times longer than they need to be.

One way to tackle this problem with our simple theme example would be to add PHP to render the theme as well. In our simple example, this wouldn’t take too long and will work fine. The content would load exactly as the menu and footer loads, then the JavaScript will load and take over. However, this would very quickly get out of hand if we tried to build a whole theme. We would be forever having to repeat ourselves, and generally getting into a massive tangle.

Already, our simple JavaScript theme is starting to get pretty messy!

In the next part of this tutorial, we’ll look at how to move from our basic theme to something more advanced, building from an altogether more stable foundation.

The Series

  1. JavaScript, jQuery and the web landscape today
  2. Introducing REST APIs
  3. Challenges in JavaScript-Based Theming
  4. Bringing React into our theme
  5. Et voila, a JavaScript WordPress theme that uses the WordPress REST API