I want to dynamically load webfonts in wordpress in theme.json

I need to allow users to select fonts from google and have use that without knowing anything about development or wordpress details. I got most of the solution but missing one critical piece to make it work: where to grab the google fonts from? I this the way to do this? I guess Webfont loader cannot help here, with the theme.json ? On the google fonts site you find the embed section and there you can see a url like https://fonts.googleapis.com/css2?family=Merriweather, googling this url allows you to find out where the .woff2 files are located. I downloaded that and added it to my plugin folder so I can reference that fontDefinition('Grey Qo', ['serif'], '400', ['file: ' . UPF_PLUGIN_DIR . 'includes/filters/grey-qo.woff2'], 'grey-qo'), where define('UPF_PLUGIN_DIR', plugin_dir_path(FILE)); is located at the root of my plugin All seems to be fine, I can see in the browser inspector window that the font is used, but it keeps on rendering Times New Roman (so it does not render the correct font but some fallback) What is missing? This is the code for it add_filter('wp_theme_json_data_theme','upfast_theme_json_filter'); function upfast_theme_json_filter($theme_json){ $fontFams=[ fontDefinition('Grey Qo', ['serif'], '400', ['file: ' . UPF_PLUGIN_DIR . 'includes/filters/grey-qo.woff2'], 'grey-qo') ]; $new_data = [ 'version' => 3, 'typography' => [ 'fontFamilies' => $fontFams, ], 'styles' => [ "typography" => [ "fontFamily" => "var(----wp--preset--font-family--grey-qo)" ] ] ]; return $theme_json->update_with( $new_data ); } class on the paragraph element for the font font included in head section of page

Comment (1)

Jese Leos

August 19, 2024

Verified user

You have an issue with your path and array structure, I fixed the code add_filter('wp_theme_json_data_theme', 'upfast_theme_json_filter'); function upfast_theme_json_filter($theme_json) { $fontFams = [ [ 'fontFamily' => 'Grey Qo', 'fontFace' => [ [ 'fontFamily' => 'Grey Qo', 'fontStyle' => 'normal', 'fontWeight' => '400', 'src' => [ 'url(' . UPF_PLUGIN_DIR . 'includes/filters/grey-qo.woff2) format("woff2")' ] ] ] ] ]; $new_data = [ 'version' => 3, 'settings' => [ 'typography' => [ 'fontFamilies' => $fontFams, ], ], 'styles' => [ 'typography' => [ 'fontFamily' => 'var(--wp--preset--font-family--grey-qo)', ], ], ]; $theme_json->update_with($new_data); return $theme_json; }

You’ll be in good company