GooFontsis a side project signed by a developer-wife and a designer-husband, both of them big fans of typography. We’ve been taggingGoogle Fontsand built a website that makes searching through and finding the right font easier.
GooFontsuses WordPress in the backend andNuxtJS(aVue.js framework)on the frontend. I’d love to tell you the story behind goofonts.com and share a few technical details regarding the technologies we’ve chosen and how we adapted and used them for this project.
Why we built GooFonts
At the moment of writing this article, there are 977 typefaces offered by Google Fonts. You can check the exact number at any moment using theGoogle Fonts Developer API.You can retrieve the dynamic list of all fonts, including a list of the available styles and scripts for each family.
The Google Fonts website provides a beautiful interface where you can preview all fonts, sorting them by trending, popularity, date, or name.
But what about the search functionality?
You can include and exclude fonts by five categories: serif, sans-serif, display, handwriting, and monospace.
You can search within scripts(likeLatin Extended, Cyrillic, or Devanagari(theyare called subsets in Google Fonts). But you cannot search within multiple subsets at once.
You can search by four properties: thickness, slant, width, and“numberof styles.”A style, also calledvariant, refers both to the style(italicor regular) and weights(100,200,up to 900). Often, the body font requires three variants: regular,bold,anditalic. The“numberof styles” property sorts out fonts with many variants, but it does not allow to select fonts that come in the“regular,bold, italic” combo.
There is also a custom search field where you can type your query.Unfortunately, the search is performed exclusively over the namesof the fonts. Thus, the resultsoften include font families uniquely from services other than Google Fonts.
Let’s take the“cartoon”query as an example. It results in“CartoonScript” from an external foundry Linotype.
I can remember working on a project that demanded two highly stylized typefaces—one evoking the old Wild West, the other mimicking a screenplay. That was the moment when I decided to tag Google Fonts.:)
GooFonts in action
Let me show you how GooFonts works. The dark sidebar on the right is your“search”area. You can type your keywords in the search field—this will perform an“AND”search. For example, you can look for fonts that are at oncecartoonand slab.
We handpicked a bunch of keywords—click any of them!If your project requires some specific subsets,check them in the subsets sections. You can also check all the variants that you need for your font.
If you like a font, click its heart icon, and it will be stored in your browser’s localStorage. You can find your bookmarked fonts on thegoofonts.com/bookmarkspage.Together with the code,you might need to embed them.
How we built it: the WordPress part
To start, we needed somekind ofinterface where we could preview and tag each font. We also needed a database to store thosetags.
I had some experience with WordPress. Moreover, WordPress comes with its REST API, which opens multiple possibilities for dealing with the data on the frontend. Thatchoice was made quickly.
I went for the most straightforward possible initial setup. Each font is a post, and we use post tags for keywords. Acustom post typecould have worked as well, but since we are using WordPress only for the data, the default content type works perfectly well.
Clearly, we needed to add all the fonts programmatically. We also neededto be able to programmatically update the fonts,including adding new ones or adding new available variants and subsets.
The approach described below can be useful with any other data available via an external API. In a custom WordPress plugin, we register a menu page from which we can check for updates from the API. For simplicity, the page will display a title, a button to activate the update and a progress bar for some visual feedback.
/** * Register a custom menu page. */ function register_custom_menu_page() { add_menu_page( 'Google Fonts to WordPress', 'WP GooFonts', 'manage_options', 'wp-goofonts-menu', function() { ?> <h1 id="Google-Fonts-API">Google Fonts API</h1> <button type="button">Run</button> <p></p> <progress max="100" value="0"></progress> <?php } ); } add_action( 'admin_menu', 'register_custom_menu_page' );
Let’s start by writing the JavaScriptpart. While most of the examples of using Ajax with WordPress implements jQuery and thejQuery.ajaxmethod, the same can be obtained without jQuery, usingaxiosand a small helperQs.jsfor data serialization.
We want toload our custom scriptinthe footer, after loadingaxiosandqs:
add_action( 'admin_enqueue_scripts' function() { wp__script( 'axios', 'https://unpkg.com/axios/dist/axios.min.js' ); wp_enqueue_script( 'qs', 'https://unpkg.com/qs/dist/qs.js' ); wp_enqueue_script( 'wp-goofonts-admin-script', plugin_dir_url( __FILE__ ) . 'js/wp-goofonts.js', array( 'axios', 'qs' ), '1.0.0', true ); });
Let’s look how the JavaScriptcould look like:
const BUTTON = document.getElementById('wp-goofonts-button') const INFO = document.getElementById('info') const PROGRESS = document.getElementById('progress') const updater = { totalCount: 0, totalChecked: 0, updated: [], init: async function() { try { const allFonts = await axios.get('https://www.googleapis.com/webfonts/v1/webfonts?key=API_KEY&sort=date') this.totalCount = allFonts.data.items.length INFO.textContent = `Fetched ${this.totalCount} fonts.` this.updatePost(allFonts.data.items, 0) } catch (e) { console.error(e) } }, updatePost: async function(els, index) { if (index === this.totalCount) { return } const data = { action: 'goofonts_update_post', font: els[index], } try { const apiRequest = await axios.post(ajaxurl, Qs.stringify(data)) this.totalChecked PROGRESS.setAttribute('value', Math.round(100*this.totalChecked/this.totalCount)) this.updatePost(els, index 1) } catch (e) { console.error(e) } } } BUTTON.addEventListener('click', () => { updater.init() })
Theinitmethod makes a request to theGoogleFonts API. Once the data from the API is available, we call the recursive asynchronousupdatePostmethod that sendsanindividual font in the POST request to the WordPress server.
Now, it’s important to remember that WordPress implements Ajax in its specific way. First of all, each request must be sent towp-admin/admin-ajax.php.This URL is available in the administration area as a global JavaScriptvariableajaxurl.
Second, all WordPress Ajax requests must include anactionargument in the data. The value of the action determines which hook tag will be used on the server-side.
In our case,the action value isgoofonts_update_post. That means what happens on the server-side is determined by thewp_ajax_goofonts_update_posthook.
add_action( 'wp_ajax_goofonts_update_post', function() { if ( isset( $_POST['font'] ) ) { /* the post tile is the name of the font */ $title = wp_strip_all_tags( $_POST['font']['family'] ); $variants = $_POST['font']['variants']; $subsets = $_POST['font']['subsets']; $category = $_POST['font']['category']; /* check if the post already exists */ $object = get_page_by_title( $title, 'OBJECT', 'post' ); if ( NULL === $object ) { /* create a new post and set category, variants and subsets as tags */ goofonts_new_post( $title, $category, $variants, $subsets ); } else { /* check if $variants or $subsets changed */ goofonts_update_post( $object, $variants, $subsets ); } } }); function goofonts_new_post( $title, $category, $variants, $subsets ) { $post_id = wp_insert_post( array( 'post_author' => 1, 'post_name' => sanitize_title( $title ), 'post_title' => $title, 'post_type' => 'post', 'post_status' => 'draft', ) ); if ( $post_id > 0 ) { /* the easy part of tagging ;) append the font category, variants and subsets (these three come from the Google Fonts API) as tags */ wp_set_object_terms( $post_id, $category, 'post_tag', true ); wp_set_object_terms( $post_id, $variants, 'post_tag', true ); wp_set_object_terms( $post_id, $subsets, 'post_tag', true ); } }
This way, in less than a minute, we end up with almost one thousand post drafts in the dashboard—all of them with a few tags already in place.And that’s the moment when the crucial, most time-consuming part of the project begins. We need to start manually add tags for each font one by one.
The default WordPress editor does not make much sense in this case. What we needed is a preview of the font. A link to the font’s page on fonts.google.com also comes in handy.
Acustom metaboxdoes the job very well. In most cases, you will use meta boxes for custom form elements to save some custom data related to the post. In fact, the content of a metabox can be practically any HTML.
function display_font_preview( $post ) { /* font name, for example Abril Fatface */ $font = $post->post_title; /* font as in url, for example Abril Fatface */ $font_url_part = implode( ' ', explode( ' ', $font )); ?> <div> <link href="<?php%20echo%20'https://fonts.googleapis.com/css?family='%20.%20%24font_url_part%20.%20'&display=swap';%20?>" rel="stylesheet"> <header> <h2><?php echo $font; ?></h2> <a href="<?php%20echo%20'https://fonts.google.com/specimen/'%20.%20%24font_url_part;%20?>" target="_blank" rel="noopener">Specimen on Google Fonts</a> </header> <div contenteditable="true" style="font-family: <?php echo $font; ?>"> <p>The quick brown fox jumps over a lazy dog.</p> <p style="text-transform: uppercase;">The quick brown fox jumps over a lazy dog.</p> <p>1 2 3 4 5 6 7 8 9 0</p> <p>& ! ; ? {}[]</p> </div> </div> <?php } add_action( 'add_meta_boxes', function() { add_meta_box( 'font_preview', /* metabox id */ 'Font Preview', /* metabox title */ 'display_font_preview', /* content callback */ 'post' /* where to display */ ); });
Tagging fonts is a long-term task with a lot of repetition. It also requires a big dose of consistency. That’s why we started by defining a set of tag“presets.”That could be, for example:
{ /* ... */ comic: { tags: 'comic, casual, informal, cartoon' }, cursive: { tags: 'cursive, calligraphy, script, manuscript, signature' }, /* ... */ }
Next with some custom CSS and JavaScript, we“hacked”the WordPress editor and tags form by enriching it with the set of preset buttons.
How we built it: The front end part (using NuxtJS)
Thegoofonts.cominterface was designed bySylvain Guizard, a french graphicandweb designer(whoalso happens to be my husband). We wanted something simplewitha distinguished“search”area. Sylvain deliberately went for colors that are not too far from the Google Fonts identity. We were looking for a balance between building something unique and originalwhileavoiding user confusion.
While Idid not hesitatechoosing WordPress fortheback-end,Ididn’t want to use it on frontend. We were aiming for an app-like experience and I, personally, wanted to code in JavaScript,usingVue.js in particular.
I came across an example of a website usingNuxtJSwith WordPress and decided to give it a try. The choice was made immediately. NuxtJS is a very popular Vue.js framework, and I really enjoy its simplicity and flexibility.
I’ve been playing around with different NuxtJS settings to end up with a 100% static website. The fully static solution felt the most performant;the overall experience seemed the most fluid.That also means that my WordPress site is only used during the build process. Thus,it can run on my localhost. This is not negligible since it eliminates the hosting costs and most of all, lets me skip the security-related WordPress configuration and relievesme ofthe security-related stress.;)
If you are familiar with NuxtJS, you probably know that thefull static generationis not(yet)a part of NuxtJS. The prerendered pages try to fetch the data again when you are navigating.
That’s why we have to somehow“hack”the 100% static generation. In this case,we are saving the useful parts of the fetched data to aJSONfile before each build process. This is possible,thanks toNuxt hooks, in particular, itsbuilder hooks.
Hooks are typically used in Nuxt modules:
/* modules/beforebuild.js */ const fs = require('fs') const axios = require('axios') const sourcePath = 'http://wpgoofonts.local/wp-json/wp/v2/' const path = 'static/allfonts.json' module.exports = () => { /* write data to the file, replacing the file if it already exists */ const storeData = (data, path) => { try { fs.writeFileSync(path, JSON.stringify(data)) } catch (err) { console.error(err) } } async function getData() { const fetchedTags = await axios.get(`${sourcePath}tags?per_page=500`) .catch(e => { console.log(e); return false }) /* build an object of tag_id: tag_slug */ const tags = fetchedTags.data.reduce((acc, cur) => { acc[cur.id] = cur.slug return acc }, {}) /* we want to know the total number or pages */ const mhead = await axios.head(`${sourcePath}posts?per_page=100`) .catch(e => { console.log(e); return false }) const totalPages = mhead.headers['x-wp-totalpages'] /* let's fetch all fonts */ let fonts = [] let i = 0 while (i { acc[el.slug] = { name: el.title.rendered, tags: el.tags.map(i => tags[i]), } return acc }, {}) /* save the fonts object to a .json file */ storeData(fonts, path) } /* make sure this happens before each build */ this.nuxt.hook('build:before', getData) }
/* nuxt.config.js */ module.exports = { // ... buildModules: [ ['~modules/beforebuild'] ], // ... }
As you can see, we only request a list of tags and a list posts.Thatmeans we only use default WordPressREST API endpoints, and no configuration is required.
Final thoughts
Working on GooFonts was a long-term adventure. It is also this kind of projects that needs to be actively maintained. We regularly keep checking Google Fonts for the new typefaces, subsets, or variants. We tag new items and update our database. Recently, I was genuinely excited to discover thatBebas Neuehas joint the family. We also have our personal favs among the much lesser-known specimens.
As a trainer that gives regular workshops, I can observe real users playing with GooFonts. At this stage of the project, we want to get as much feedback as possible. We would love GooFonts to be a useful, handy and intuitive tool for web designers.One of the to-do features is searching a font by its name. We would also love to add a possibility to share the bookmarked sets and create multiple“collections”of fonts.
As a developer, I truly enjoyed the multi-disciplinary aspect of this project. It was the first time I worked with the WordPress REST API, it was my first big project in Vue.js, and I learned so much about typography.
Would we do anything differently if we could? Absolutely. It was a learning process. On the other hand, I don’t think we would change the main tools. The flexibility of both WordPress and Nuxt.js proved to be the right choice. Starting over today, I would definitely took time to exploreGraphQL,and I will probably implement it in the future.
I hope that you find some of the discussed methods useful. As I said before, your feedback is very precious. If you have any questions or remarks, please let me know in the comments!
The above is the detailed content of How We Tagged Google Fonts and Created goofonts.com. For more information, please follow other related articles on the PHP Chinese website!

For a while, iTunes was the big dog in podcasting, so if you linked "Subscribe to Podcast" to like:

We lost Opera when they went Chrome in 2013. Same deal with Edge when it also went Chrome earlier this year. Mike Taylor called these changes a "Decreasingly

From trashy clickbait sites to the most august of publications, share buttons have long been ubiquitous across the web. And yet it is arguable that these

In this week's roundup, Apple gets into web components, how Instagram is insta-loading scripts, and some food for thought for self-hosting critical resources.

When I was looking through the documentation of git commands, I noticed that many of them had an option for . I initially thought that this was just a

Sounds kind of like a hard problem doesn't it? We often don't have product shots in thousands of colors, such that we can flip out the with . Nor do we

I like when websites have a dark mode option. Dark mode makes web pages easier for me to read and helps my eyes feel more relaxed. Many websites, including

This is me looking at the HTML element for the first time. I've been aware of it for a while, but haven't taken it for a spin yet. It has some pretty cool and


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

SublimeText3 English version
Recommended: Win version, supports code prompts!

WebStorm Mac version
Useful JavaScript development tools

SublimeText3 Linux new version
SublimeText3 Linux latest version