Register a Self-Hosted Font in theme.json
Adds a font family with your own font files (stored in uploads/fonts) to the theme's typography settings, so it appears in the editor's font picker and loads without Google.
Opens WPIDE on
Code
// Font settings. Files live in wp-content/uploads/fonts/.
$wpide_font = array(
'name' => 'Inter',
'slug' => 'inter',
'fallback' => 'system-ui, -apple-system, sans-serif',
'files' => array(
'400' => 'inter-400.woff2',
'700' => 'inter-700.woff2',
),
);
add_filter( 'wp_theme_json_data_theme', function ( $theme_json ) use ( $wpide_font ) {
$uploads = wp_get_upload_dir();
$base = trailingslashit( $uploads['baseurl'] ) . 'fonts/';
$faces = array();
foreach ( $wpide_font['files'] as $weight => $file ) {
if ( ! file_exists( trailingslashit( $uploads['basedir'] ) . 'fonts/' . $file ) ) {
continue;
}
$faces[] = array(
'fontFamily' => $wpide_font['name'],
'fontWeight' => (string) $weight,
'fontStyle' => 'normal',
'fontDisplay' => 'swap',
'src' => array( $base . $file ),
);
}
if ( ! $faces ) {
return $theme_json;
}
$data = $theme_json->get_data();
$families = isset( $data['settings']['typography']['fontFamilies'] ) ? (array) $data['settings']['typography']['fontFamilies'] : array();
$families = isset( $families['theme'] ) ? (array) $families['theme'] : $families;
$families = array_values( array_filter( $families, function ( $family ) use ( $wpide_font ) {
return ! isset( $family['slug'] ) || $family['slug'] !== $wpide_font['slug'];
} ) );
$families[] = array(
'name' => $wpide_font['name'],
'slug' => $wpide_font['slug'],
'fontFamily' => '"' . $wpide_font['name'] . '", ' . $wpide_font['fallback'],
'fontFace' => $faces,
);
return $theme_json->update_with( array(
'version' => WP_Theme_JSON::LATEST_SCHEMA,
'settings' => array( 'typography' => array( 'fontFamilies' => $families ) ),
) );
} );
Notes
Upload the .woff2 files to wp-content/uploads/fonts/ first and match the file names below. Works with block themes and classic themes that use theme.json.
How to add this snippet
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.