How to add typographic fonts to WordPress block themes

The easy and compliant way that every theme developer should know.

TL;DR: Use the Create Block Theme plugin to bundle fonts in your theme with just a few clicks.

WordPress block themes allow you to add fonts to a theme by adding the font file assets to the theme folder and referencing them in the theme.json. Editing a JSON file manually does not deliver the best user experience. The good news is you can use the plugin to make this task much simpler without technical trade-offs.

Disclaimer: The plugin is for development only and is not intended for live production websites because it modifies the currently active theme. It was conceived as a tool to create new production-ready themes.

Step by Step

  1. Install the Create Block Theme plugin.
  2. Activate the theme you want to manage.
  3. Go to Appearance -> Manage Theme Fonts.
  4. Add/Remove the font faces you want.

FAQS

How are the fonts bundled in my theme?

The plugin stores the font assets in a sub-folder of your theme ( <your-current-theme>/assets/fonts/ ) and adds font family definitions to your theme.json file. This is the case no matter if you upload a local font asset or use the Add Google Font option.

The plugin removes both the theme.json definition and the font assets if you remove a font face.

How are the fonts enqueued?

WordPress takes the font faces you added using the plugin, which are listed in your theme.json, and automatically converts them to CSS font face definitions which are included in the HTML page downloaded by the user browser.

Will adding many fonts make my theme too heavy?

Yes and no, or not necessarily. That can be counter-intuitive so let’s explore it in more detail. 

WordPress references all the font files needed in your site CSS to let the browser know what font assets may need to download.

Even though WordPress references many fonts, modern browsers are optimized to only download the fonts that are used in the page being loaded. It is important to note that browsers calculate this considering just the current page loaded and not on a site-wide basis.

For example, if you include an ultra-thin variant of the Inter font family, but there is not a single element (ex: paragraphs, links, etc.) using Inter ultra-thin variant, the browser will not download this font asset. In this case, the performance penalty for including this font is nearly zero.

Should I add a massive quantity of font faces to my theme “just in case”?

No, both from a performance and design perspective, having a good font pair is always advisable over a proliferation of too many different fonts. Also, if the font is not in use, what’s the point of including it?

There is no magical number of font faces you can or should include. But usually, less is more. Sticking to the minimal quantity required to implement the aesthetics you are looking for is always a good idea.

Can I include variable fonts in my theme?

As with any other font file, you can add variable font assets using the “Add Local Font” option. The plugin will add the font definition and asset just like any other type of font. You can use it just like that or adjust more options related to variable fonts by editing the theme.json file.

Is this solution GDPR compliant?

Yes, because the plugin bundles the font files in your theme, and your WordPress instance will serve them. No third-party servers or tracking technologies are involved in serving the fonts to your users. You don’t need to request extra permissions from your users to include the fonts.

More info

Do you need a more detailed step-by-step guide? No worries! Check out this great video tutorial about how to use the plugin.

Follow up

Have any questions about fonts and themes? Ask in the comments!

Creating a Block-based Landing Page Theme

Kjell Reigstad details how to build a single-page block-based theme.

The other day, my colleague Ian Stewart and I were discussing homepage templates, and this Carrd layout came up in conversation:

Layout from Carrd.co

Its two-column design is friendly and simple. It’s also drastically different than most WordPress themes we see these days — it doesn’t have a traditional header and footer, or even a menu for that matter. It really doesn’t look like a WordPress site (partly because it isn’t. 😄).

It does however look like a relatively simple pattern that could be built with Gutenberg blocks. With block-based themes on the horizon, Ian suggested I see how easy it would be to build a block-based theme featuring a similar homepage layout. I took him up on the challenge.

In about an hour, I had a fully functional version of the theme. Read on for details on how it all came together.


The Structure

The first thing I did was set up the basic theme files, and get them all hooked up to each other. Most of the theme files are more or less boilerplate — aside from a little CSS and some experimental-theme.json value changes, they aren’t going to change much from theme to theme. Here’s how that looked:

- assets
 	- (font files)
- block-templates
 	- index.html
- experimental-theme.json
- functions.php
- index.php
- style.css
- style-shared.css

HTML

  • block-templates/index.html was left empty to start with. As explained below, I populated this using Gutenberg.

JSON

PHP Files

  • index.php is empty, but needs to be there.
  • functions.php contains a standard function to enqueue the stylesheet. Aside from that, it just sets some theme options. Since this is an experimental block-based theme, I opted-in to just about all of the experimental options from the Block Editor handbook.

Stylesheets

  • style.css is enqueued only on the front-end. It includes a standard theme header docblock, plus barebones alignment styles, courtesy of Ari Stathopoulos. These styles just replicate the editor alignment rules from Gutenberg (standard, wide, and full) in the front-end. Hopefully Gutenberg can provide these styles one day, eliminating the need for this standalone CSS file.
  • style-shared.css houses the basic font and color rules, plus just a few theme-specific spacing overrides. This is loaded in both the editor and the front-end.

Building the Front Page Template

Once I had those files in place, I was ready to build the block template in block-templates/index.html.

First, I installed and activated my theme. With the empty HTML file created, I opened up the site editor, and was presented with a blank slate:

The Gutenberg site editor, with no content.

From here, I added a full-width columns block. On the left, I used a Cover block and uploaded my image. I used a columns block because I wanted to take advantage of two great Cover block features: its ability to take up the full height of the screen, and also its focal point picker which would ensure that the image is always centered on the model’s face.

The Gutenberg site editor with a cover block inserted into the left two thirds of the screen.

After that, I added a few center-aligned blocks to the right column: Site Title and Site Tagline blocks, a Button block, and a Social Links block:

The Gutenberg site editor with a Cover block on the left side, and a site title, description, button, and a set of social links on the right.

From there, I hit “Update Design” and used the Gutenberg plugin’s “Export” tool to download a zip file containing this template:

The "Export" option in the Gutenberg Plugin.

The resulting zip file included an index.html file containing the block markup I had just built. I replaced my empty block-templates/index.html file with this new one, and I had a fully functional single-page block-based theme! 🎉


Viewing the Final Result

The only thing left to do was check out the site in the front end. I was pleased with how similar everything looked to the editor, and how the whole layout was responsive by default.


This exercise made me truly excited about the future of theming. It took very little time to assemble the boilerplate necessary to get started, and I constructed most of the theme the editor itself. I imagine whole process will only get faster (and the boilerplate will be whittled down further) as full-site editing progresses.

The theme is available to test by visiting the Theme Experiments repository. There, you’ll find this as well as other themes like the new block-based version of Twenty Twenty-One.

For more in-depth details on building a block-based theme, visit the official tutorial in the Block Editor Handbook.

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

How to add Google fonts to WordPress themes

When enqueuing Google fonts, there are five things to consider:

  1. Is the font enqueued instead of included directly in the template files or CSS?
  2. Is the font enqueued on the correct hook?
  3. Is the font URL protocol independent?
  4. Can translators deactivate the font if their language’s character set isn’t supported?
  5. Can the font be dequeued by child themes?

In this post, we’ll go over the best practices for enqueuing Google fonts in your WordPress theme. Continue reading “How to add Google fonts to WordPress themes”

HTML5 Galleries in WordPress 3.9

With the new release of WordPress will come the ability to declare support for HTML5 markup in galleries. Once a theme declared support, the definition list elements will be replaced by <figure> and <figcaption> for better semantics.

If you decide to not only adopt this new feature but also maintain backwards compatibility, then there are two ways to achieve that:

  1. Style not only the new HTML5 elements, but also add CSS selectors for the traditional definition list elements. This is the route we chose for _s to keep it as simple as possible.
  2. Filter the shortcode attributes and override the tag parameters. Since the shortcode_atts_gallery filter was introduced in 3.6, you’ll be backwards compatible with the latest two versions.

Continue reading “HTML5 Galleries in WordPress 3.9”

Validation and Sanitization in the Customizer

At Automattic, we exclusively use the Customizer for theme options instead of theme option pages. We believe that themes should only alter the display of content and should not add any additional functionality that would be better suited for a plugin. Since all options are presentation centered, they should all be controllable by the Customizer.

Continue reading “Validation and Sanitization in the Customizer”

The WordPress.com Public Theme Guide

wpcom-theme-guidelines

They say Valentine’s Day is all about love. Well, the thing I love the most about working on the Theme Team at Automattic is the attention to detail that goes into each theme launch. There is an inital build process followed by a series of peer reviews. More times than not a theme will be put under the microscope of 2, 3, or sometimes 4 different team members before launch. The sheer number of things that can potentially go awry in a theme can be overwhelming at times. This review process allows us to catch as many bugs as possible before people start using our themes.

Our peer reviews focus on a mixture of three areas: code quality, usability, and discovery of theme-specific anomalies. Over the years, our review process has grown organically. When we discover a new issue we will generally post about it to an internal P2-powered website for team discussion. While this process works really well, it can be a bit time-consuming to navigate through three years’ worth of posts to find an isolated conversation about a particular issue.

Recently, we thought it was a good idea to collect all of our theme guidelines and create an easy-to-follow resource. Instead of posting this internally, we decided that we would like to share our guidelines with theme developers everywhere. I would like to present to you the first installment of The WordPress.com Public Theme Guide. We hope that you get as much use out of this as we do!

Theme Code Matters, Too

Hey there, WordPress theme developers. When you’re crafting themes, are you checking the quality of your theme code? The design is important, yes, but so is the code.

Hey there, WordPress theme developers. When you’re crafting themes, are you checking the quality of your theme code? The design is important, yes, but so is the code. Within the past year, the WordPress theme review team has been hard at work encouraging best coding practices among WordPress theme developers, with the goal of raising the overall standard of the themes that appear in the WordPress.org theme repository. Even if you don’t intend to submit your theme to the WordPress.org theme repository, it’s wise to develop your themes as though that was your intention. I hope that by the end of this post, you’ll have a better understanding of the benefits of doing so.

The WordPress Theme Review Team and its guidelines

Just in case this is the first time you’ve heard of the theme review team, I’ll describe it briefly. They’re a group of volunteers from the WordPress community that reviews each theme that is submitted to the WordPress.org theme repository to check for compliance with the guidelines and standards that they have set forth. I’m not going to list all of the guidelines here because you can read them at the theme review team’s website, but I do wish to highlight a few here because they’re especially relevant to coding practices:

Briefly, a description of each of the above:

The Theme Check plugin

This is a plugin that tests your theme to see if it meets the latest theme review guidelines. If your theme is missing a required or recommended feature, or if it contains deprecated functions, the plugin will let you know and suggest possible fixes.

Code quality

These are a general set of guidelines that specify how you should format the HTML, CSS, and PHP in your theme. All HTML and CSS mark-up must validate to W3C Standards, and your PHP must neither generate any notices, warnings, or errors when WP_DEBUG is turned on (turn it on by placing  define('WP_DEBUG', true) in wp-config.php).

Does your theme contain hidden PHP warnings like THIS?

The Theme Unit Test

How well does your theme handle posts without titles? Do images resize properly? Do floated elements inside posts clear properly? Are all possible HTML tags that users can use in the visual editor styled? Are all widgets styled? The theme unit test is a set of sample data that you can use to test your theme in scenarios such as these.

Example of a Unit Test post on the Twenty Eleven Theme
Example of a Unit Test post on the Twenty Eleven Theme

Of course, as I stated earlier, these are just three of the areas in the theme review guidelines. A theme passes its review and is accepted in the WordPress.org theme repository when it satisfies the criteria for all of the areas.

So, why should you care?

The theme review team’s guidelines are important for all WordPress theme developers for three basic reasons:

  1. They establish general consistency among WordPress themes for users and developers.
  2. They ensure protocols for theme security.
  3. They raise the bar for overall theme quality.

Let’s discuss these three areas in more detail.

Consistency

WordPress themes are a eclectic bunch, but they do have at least one thing in common — they are all WordPress themes. It’s important to always keep this in mind.

When your theme deviates too far from the core WordPress functionality, you run the risk of users becoming frustrated as to why certain features that they’ve come to expect from WordPress don’t seem to work with their site. Listed below are sections of the theme review guidelines that help establish a base consistency among themes in the WordPress.org theme repository:

Before you add a custom feature to your theme, check to see if WordPress already has a core function that can take care of it. The table below highlights core features your theme should utilize as much as possible.

Theme Feature WordPress Feature to Use
Custom Logo/Banner Custom Headers
Background Color/Image Custom Background
Menu Management WordPress Navigation Menus
Theme file editing WordPress Theme Editor and Plugin Editor
Theme Options Page Settings API
Theme Options Page Design Stick with the WordPress UI instead of making your own design. (Ryan Imel from WPCandy wrote a blog post on this subject)
Design options (color pickers, font size tools, border size, etc) Keep to a minimum. Encouraging users to make design changes with CSS is more scalable in the long run.
Direct Database Queries WordPress Template Tags and Functions
Thumbnails Post Thumbnails (Featured Images)

Security

Constant Vigilance: Keeping themes secure requires active, continuous effort

Themes play a large role in WordPress sites, so it pays to ensure that your theme’s code is as secure as possible. Don’t let your theme be the one that leaves your users’ sites vulnerable to hackers. No one wants (or deserves) to have their site hacked. If you follow the theme review team’s security-related guidelines, you will be one step closer to building a theme that is as safe as it is gorgeous. The following are the theme review team’s guidelines related specifically to security. I highly recommend that you read them as you develop your theme:

  • Theme Settings and Data Security – Properly escaping all data throughout your theme and using the Settings API for theme options pages are essential characteristics of a secure theme.
  • Theme Obsolescence – Outdated code and deprecated functions are a security threat because they may contain known vulnerabilities that hackers can exploit. Themes in the WordPress.org repository will be removed if they are not updated on a regular basis to comply with the latest version of WordPress. In a similar vein, third-party scripts can also pose security risks, as we saw with the recent TimThumb vulnerability. If you use third-party scripts in your theme, please, please, please check those scripts regularly to make sure they are up to date. If the original author of a script does not put out regular updates, think twice about using it. Security is never a “set it and forget it” deal — you must approach it Mad-Eye Moody-style: CONSTANT VIGILANCE.

Quality

The final reason that it’s important to pay attention to your theme’s code is for the sake of quality. A theme that uses well-formed, modern code is easier for you and other developers to maintain in the future. The larger the number of well-coded themes we have, the more positively this reflects on the WordPress community as a whole. The following area from the theme review team’s guidelines relates specifically to code quality (I linked it earlier, but I’m linking it again because it’s that important):

In addition, WordPress has adopted standards for writing PHP, HTML, and CSS. We use these standards when converting themes for use on WordPress.com:

Conclusion and … how to get started

I hope I’ve convinced you why it’s so important to pay attention to your theme’s code, whether you are creating free themes or commercial themes. If you’re interested in applying some of these principles to your theme development, here is a nice list of procedures to keep in mind during the development process:

  • Make sure you’re aware of the current theme review guidelines.
  • Look at the code of the current default theme, such as Twenty Eleven, as a starting point and as an example of best coding practices and implementing core WordPress functionality.
  • Get in the habit of testing your theme with the unit test data.
  • Turn on WP_DEBUG in wp-config.php to check for hidden errors, warnings, and notices.
  • Install the Theme Check, Log Deprecated Functions, and Debug Bar  plugins. Run their tests often to catch (and fix) potential problem areas before they pile up.
  • Before you add a custom function, check to see if there is a WordPress core function that can take care of it. If you feel that the WordPress core functionality is lacking somehow, try supplementing the core feature instead of replacing it completely. Make sure that any custom feature you add does not leave “debris” behind (such as broken shortcodes) or otherwise cause a site to break badly if users decide to switch their theme. What are your “fallback” features?
  • Consider joining the WordPress theme review team, which forces you to learn by checking others’ code. For more information, please read Justin Tadlock’s excellent post on this subject: Join the WordPress theme review team.

Resources for further reading

Using TextMate for WordPress Code Cleanup

I spend a lot of time cleaning up WordPress themes. During the code cleanup I often perform certain cleanup tasks over and over, which makes them perfect for TextMate commands.

In this post I’ll show you how to add two useful commands to TextMate, then move through the steps I take for theme code cleanup and put the commands into practice.

First, let’s add the commands to a TextMate bundle. If you don’t know how to add commands to a TextMate bundle, or don’t have your own bundle set up yet, start here and add a new bundle. I usually add my own commands to a bundle called @lance so it sticks to the top of my bundle list.

Continue reading “Using TextMate for WordPress Code Cleanup”