Table of Contents
Why we built GooFonts
GooFonts in action
How we built it: the WordPress part
Google Fonts API
How we built it: The front end part (using NuxtJS)
Final thoughts
Home Web Front-end CSS Tutorial How We Tagged Google Fonts and Created goofonts.com

How We Tagged Google Fonts and Created goofonts.com

Apr 12, 2025 pm 12:02 PM

How We Tagged Google Fonts and Created goofonts.com

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' );
Copy after login


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 );
});
Copy after login

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()
})
Copy after login

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 );
  }
}
Copy after login

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 */
  );
});
Copy after login

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'
  },
  /* ... */
}
Copy after login

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)
}
Copy after login
/* nuxt.config.js */
module.exports = {
  // ...
  buildModules: [
    ['~modules/beforebuild']
  ],
// ...
}
Copy after login

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!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Making Your First Custom Svelte Transition Making Your First Custom Svelte Transition Mar 15, 2025 am 11:08 AM

The Svelte transition API provides a way to animate components when they enter or leave the document, including custom Svelte transitions.

Working With GraphQL Caching Working With GraphQL Caching Mar 19, 2025 am 09:36 AM

If you’ve recently started working with GraphQL, or reviewed its pros and cons, you’ve no doubt heard things like “GraphQL doesn’t support caching” or

Show, Don't Tell Show, Don't Tell Mar 16, 2025 am 11:49 AM

How much time do you spend designing the content presentation for your websites? When you write a new blog post or create a new page, are you thinking about

Building an Ethereum app using Redwood.js and Fauna Building an Ethereum app using Redwood.js and Fauna Mar 28, 2025 am 09:18 AM

With the recent climb of Bitcoin’s price over 20k $USD, and to it recently breaking 30k, I thought it’s worth taking a deep dive back into creating Ethereum

Creating Your Own Bragdoc With Eleventy Creating Your Own Bragdoc With Eleventy Mar 18, 2025 am 11:23 AM

No matter what stage you’re at as a developer, the tasks we complete—whether big or small—make a huge impact in our personal and professional growth.

A bit on ci/cd A bit on ci/cd Apr 02, 2025 pm 06:21 PM

I&#039;d say "website" fits better than "mobile app" but I like this framing from Max Lynch:

Vue 3 Vue 3 Apr 02, 2025 pm 06:32 PM

It&#039;s out! Congrats to the Vue team for getting it done, I know it was a massive effort and a long time coming. All new docs, as well.

What the Heck Are npm Commands? What the Heck Are npm Commands? Mar 15, 2025 am 11:36 AM

npm commands run various tasks for you, either as a one-off or a continuously running process for things like starting a server or compiling code.

See all articles