WordPress / google-fonts-to-wordpress-collection

Gets the Google fonts collection and transform it to a WordPress font library collection, including SVG previews
16 stars 5 forks source link

Google Fonts collection to WordPress Font Library collection

This repo contains node.js scripts to generate the Google Fonts collection JSON and associated font previews for the WordPress Font Library.

Here are examples of the JSON files these scripts generate:

How?

The code in this repo:

Instructions

Install the NPM dependencies:

npm install

GOOGLE_FONTS_API_KEY=abc123 npm run api

npm run previews

Development server

To serve the fonts from a development server for testing on a local WordPress site:

Start the development server from this repo

npm run serve

Add the following filters to an mu-plugin running on your local WordPress site (e.g. wp-content/mu-plugins/0-local.php). Update the version variables, if needed:

// Rewrite Google Fonts URLs to localhost.
function my_local_google_fonts_collection( $pre, $args, $url ) {
    $wp_release_fonts_version = '6.5';
    $gutenberg_release_fonts_version = '17.7';
    $generated_fonts_version = '18.2';

    if ( str_starts_with( $url, 'https://s.w.org/images/fonts/' ) ) {
        $url = str_replace( "https://s.w.org/images/fonts/wp-$wp_release_fonts_version", "http://localhost:9158/images/fonts/$generated_fonts_version", $url );
        $url = str_replace( "https://s.w.org/images/fonts/$gutenberg_release_fonts_version", "http://localhost:9158/images/fonts/$generated_fonts_version", $url );
        $http = new WP_Http();
        return $http->request( $url, $args );
    }

    return $pre;
}
add_filter( 'pre_http_request', 'my_local_google_fonts_collection', 10, 3 );

// Allow serving fonts locally for testing.
function my_allow_localhost( $allow, $host, $url ) {
    if ( str_starts_with( $url, 'http://localhost:9158/images/fonts/' ) ) {
        $allow = true;
    }

    return $allow;
}
add_filter( 'http_request_host_is_external', 'my_allow_localhost', 10, 3 );

// Allow port 9158 for local fonts server.
function my_allow_http_ports( $ports ) {
    $ports[] = 9158;
    return $ports;
}
add_filter( 'http_allowed_safe_ports', 'my_allow_http_ports' );

The local WordPress site should now load fonts from this repo. You can check by loading the Font Library in the site editor and looking at the log output from npm run serve.

Extra utilities:

Download all the font files

npm run files

Requirements

Creating a new version of the font collection

Update the CURRENT_RELEASE and SVG_PREVIEWS_BASE_URL constants in src/constant.js with the new version.

Generate a new version of the collection using the commands above, generate new previews if needed, and open a PR with the change.

Once the PR is merged to trunk, the collection can be uploaded to the s.wp.org CDN by submitting a meta ticket, for example: https://meta.trac.wordpress.org/ticket/7522