Cannot Preload Font in WordPress - wordpress

I spent a couple of hours and could not find any solution for this. I am trying to preload Elegant Icons font with .woff extension and I think i am doing everything correctly, however, Google Page Speed Insights still finding issues:
"We recommend that you use <link rel = preload> to specify earlier
retrieval of resources".
I can see that the icons from the font get loaded on the frontend, however, according to Google Page Speed Insights, the font is still not preloaded. Any help will be much appreaciated. Here is my code in functions.php:
function my_fonts() {
//Add Elegant Icons font
wp_enqueue_style( 'elegant-icons-font', get_template_directory_uri() . '/assets/font/ElegantIcons.woff' );
//Add Elegant Icons css
wp_enqueue_style( 'elegant-icons', get_template_directory_uri() . '/assets/css/elegantIcons.css' );
}
add_action( 'wp_head', 'my_fonts' );
/* Preload Icons font */
function my_font_loader_tag_filter($html, $handle) {
if($handle === 'elegant-icons-font' ) {
return str_replace("rel='stylesheet'", "rel='preload' as='font' type='font/woff2' crossorigin='anonymous'", $html);
}
return $html;
}
add_filter('style_loader_tag', 'my_font_loader_tag_filter',10, 2);
In Elegant Icons css i have
#font-face {
font-family: 'ElegantIcons';
src: url('../fonts/ElegantIcons.woff') format('woff'),
url('../fonts/ElegantIcons.ttf') format('truetype');
font-weight: normal;
font-style: normal;
font-display: swap;
}
If i remove the src property from the css file, the icons do not display on the frontend anymore. I even tried hardcoding the link with preload attribute in the site header but Google Page Speed insights is still not happy. I really ran out of any ideas.

Related

How to find css classes (in e.g. chrome dev tools) that use a specific font-family?

I'm currently in the process of updating all my websites from using webfonts to hosting the fonts locally by myself. This process is a little bit frustrating, because I often can't find the css classes of the webfonts. At the moment, it's more a "try and error" kind of thing, where I'm just klicking trough the google chrome dev tools and looking for the corresponding css classes. So I was wondering if there is a simple way to look in a published website via browser for the css classes of a specific font family? (I cannot search for the classes in the IDE, because in this use case the websites where developed with webflow)
EDIT: The websites in question were created with a "building block" system called "Webflow". There, the fonts are selected via graphical interfaces. Now the problem is that somewhere in these old and huge web pages there are CSS classes that use the "Lato webfont". I want to replace this font, but I can't search for used fonts in this graphical interface. What I can search for are the CSS classes. So my idea was to use the Chrome Dev Tools to find out which CSS classes used the Lato font to ultimately replace it.
Find css rules by properties
If you can't edit you site's css files globally you might at least get some sort of "cheat sheet" containing all selectors matching certain property values.
let cssRules = getCssRules();
let filterLato400 = findRulesByProperties(cssRules, {
"font-family": "Lato",
});
console.log(filterLato400);
let filterLato400Italic = findRulesByProperties(cssRules, {
"font-family": "Lato",
"font-weight": 400,
"font-style": "italic"
});
console.log(filterLato400Italic);
//get all css rules in document
function getCssRules() {
let cssText = "";
let rules = [
...(document.styleSheets[0].rules || document.styleSheets[0].cssRules)
];
let cssArr = [];
rules.forEach(function(rule) {
let selector = rule.selectorText;
let cssText = rule.cssText;
if (selector && cssText) {
let properties = cssText
.replace(selector, "")
.replace(/[{}]/g, "")
.split(";")
.map((val) => {
return val.trim();
})
.filter(Boolean)
.map((vals) => {
return vals.split(":");
});
cssArr.push({
selector: selector,
properties: properties
});
}
});
return cssArr;
}
//filter css rules by properties
function findRulesByProperties(css, filters) {
let classList = [];
css.forEach(function(rule) {
let selector = rule.selector;
let props = rule.properties;
let vals = [];
let valsFilter = [];
for (let key in filters) {
let filterName = key;
let filterValue = filters[key];
valsFilter.push(filterValue.toString());
}
for (let i = 0; i < props.length; i++) {
let prop = props[i];
let propName = prop[0];
let propValue = prop[1].trim();
if (valsFilter.indexOf(propValue) != -1) {
vals.push(propValue);
}
}
if (vals.length == valsFilter.length) {
classList.push(selector)
}
});
return `results ${classList.length}: ${classList.join(", ")} || match: ${JSON.stringify(filters)}`;
}
body {
font-family: Georgia;
}
h1 {
font-family: "Lato";
font-weight: 700;
}
h2 {
font-family: "Lato";
font-weight: 400;
}
.classLato400 {
font-family: "Lato";
font-weight: 400;
}
.classLato400italic {
font-family: "Lato";
font-weight: 400;
font-style: italic;
}
.classLato700 {
font-family: "Lato";
font-weight: 700;
}
.classRoboto400 {
font-family: "Roboto";
font-weight: 400;
}
In the above example we're searching for all rules containing font-family:Lato (and other filters like font-weight or font-style).
You could paste your main css file in the snippet to get a list of selectors matching all criteria.
Replace external #font-face rules
If I got you right and your ultimate goal is to replace externally hosted font files with local ones (e.g. to improve GDPR compliance), you don't need to get every css font-family class reference.
The most important part are the #font-face rules that are actually responsive for downloading font files.
OK that's not perfectly correct since a font file won't be downloaded unless some DOM element uses this particular font-family.
In other words, your css might actually contain a plethora of unused font-families – on the other hand if they aren't used anywhere they won't be downloaded (so browsers have a default lazyloading method for fonts).
Example: you need to replace google webfonts with locally hosted fonts
Open your devTools and switch to the "Font" tab
Now you can see a list of all downloaded font files as well as their origin (URL) and their "Initiator" – the source file, that initiated the file download. Usually this would be a <link> stylesheet reference or an #import rule within your css, but it can also be a javaScript font loader method.
By inspecting the "URL" column, we can clearly see if a font is loaded from an external host.
Clicking the "Initiator" row/entry will open the file triggering the download – this will either be a file (like a .css) you want to completely remove or just a portion of a css file (take a closer look at #font-face rules, especially the src properties).
Following the google webfonts use case/example
(actually pretty similar to other font delivery services)
obviously we need to get local copies of my previously externally hosted font files –
google web font helper might be helpful to get a ready-to-go #font-face css and a download package including all needed font files.
we need to delete all css files or #font-face or #import rules that are still referring to external file sources and replace them with custom local font file urls.
Possible shortcuts to remove external font file references:
Check your HTML/template head for undesired elements like these
(so containing an external URL like "fonts.googleapis.com"):
<link href="https://fonts.googleapis.com/css2?family=Roboto:wght#400;700" rel="stylesheet">
or within inline <style> tags for #import rules like #import url('https://fonts.googleapis.com/css2?family=Roboto:wght#400;700')
or similar #import rules within your main css file – they should usually be found at the top of your css code.
Delete these references and replace with custom #font-face rules like so (example is based on google web font helper output using "Roboto" font-family and font-weights 400+700 ... regular and bold).
/* roboto-regular - latin */
#font-face {
font-family: 'Roboto';
font-style: normal;
font-weight: 400;
src: url('fonts/roboto-v30-latin-regular.woff2') format('woff2');
}
/* roboto-700 - latin */
#font-face {
font-family: 'Roboto';
font-style: normal;
font-weight: 700;
src: url('fonts/roboto-v30-latin-700.woff2') format('woff2');
}
Inspect the network tab once again
If everthing is working fine we should see the locally retrieved font files for each style (e.g. regular, bold, italic, bold italic etc.)
If not: double check your file paths!
Seriously, this is probably the most common source of errors. (e.g "../fonts/" or "./fonts/" or just "fonts/").

Remove embedded stylesheet for Gutenberg editor on the back end

The Gutenberg editor comes with an embedded stylesheet. Here's a snippet from that stylesheet:
...
.editor-styles-wrapper {
font-family: "Noto Serif", serif;
font-size: 16px;
line-height: 1.8;
color: #191e23;
}
.editor-styles-wrapper p {
font-size: 16px;
line-height: 1.8;
}
...
I've enqueued my own editor stylesheet using the following:
add_action("enqueue_block_editor_assets", "enqueue_custom_block_editor_assets");
function enqueue_custom_block_editor_assets() {
wp_enqueue_style("editor-style", get_stylesheet_directory_uri()."/editor-style.css", null, null);
}
Since I have my own editor stylehseet, I'd like to get rid of the default one. A search on this topic yields lots of results for removing default block styling on the front end, but I'm referring to the editor styling on the back end. Thanks for your help!
I drilled down into how it was being injected and found a way to nuke it out via the block_editor_settings filter. There is a styles key with an array that contains the css. The only iffy thing about this for me is that I'm assuming the shape of the array will always be the same, I should be doing some type of check here.
add_filter( 'block_editor_settings' , 'remove_guten_wrapper_styles' );
public function remove_guten_wrapper_styles( $settings ) {
unset($settings['styles'][0]);
return $settings;
}
My solution was a workaround to automatically override any styles within the .editor-styles-wrapper. Using LESS:
editor-style.css
.editor-styles-wrapper {
#import "style.less";
}
I would still love to disable that embedded stylesheet though, if anyone knows how to do that.

CSS font-variation-settings not working

I'm currently experimenting with variable fonts. My first test was to experiment with the font-variation-settings directive, but it seems that is not working. Both on Codepen:
https://codepen.io/DailyMatters/pen/LrBvmz
This is my current CSS (it seems like the font is being loaded correctly from dropbox):
#font-face {
font-family: 'SourceSans';
src: url('https://www.dropbox.com/s/fmonith639cs931/SourceSansVariable-Roman.ttf') format('truetype');
}
html {
font-family: 'SourceSans', sans-serif;
}
p {
font-variation-settings: "wght" 999, "wdth" 125;
}
But also on Chrome.
As much as I change the "wght" axis, nothing happens. I did same tests with this same font using #font-face, and it worked on Chrome. Any reason this is not working with font-variation-settings?

I want to add google fonts in function file of theme

I want to add fonts to my theme. So i have used the bellow code for this.
function load_fonts() {
wp_register_style('et-googleFonts', 'http://fonts.googleapis.com/css?family=Open+Sans:300italic,400italic,700italic,400,700,300');
wp_register_style('et-googleFonts', 'http://fonts.googleapis.com/css?family=Helvetica:300italic,400italic,700italic,400,700,300');
wp_enqueue_style( 'et-googleFonts');
}
add_action('wp_print_styles', 'load_fonts');
So i have to use many fonts like Helvetica, Palatino and Trebuchet in the function. But i dont know how to add those fonts.
Try this
function theme_assets() {
wp_enqueue_style( 'et-googleFonts', "http://fonts.googleapis.com/css?family=Open+Sans:300italic,400italic,700italic,400,700,300" );
wp_enqueue_style( 'et-googleFonts1', "http://fonts.googleapis.com/css?family=Helvetica:300italic,400italic,700italic,400,700,300" );
}
add_action( 'wp_enqueue_scripts', 'theme_assets' );
Also there must be wp_head() in your header file to make this work.!

Google font not rendering in WordPress site

I'm working with in WordPress and Google Fonts isn't rendering aside from on my Macbook (Chrome and Firefox).
I'm using the #import method for Archivo Narrow. Sample code is below:
#import url('https://fonts.googleapis.com/css?family=Archivo+Narrow:400,400i,700');
h1 {font-family: 'Archivo Narrow', sans-serif; font-size:48px; color:#012233; font-weight:bold;}
Website in question is the following: eptestdev.us/northpage
Adding the font via your theme’s functions.php
function wpb_add_google_fonts() {
wp_enqueue_style( 'wpb-google-fonts', 'https://fonts.googleapis.com/css?family=Archivo+Narrow:400,400i,700', false );
}
add_action( 'wp_enqueue_scripts', 'wpb_add_google_fonts' );
wpbeginner.com how-add-google-web-fonts-wordpress-themes

Resources