How to Replace CSS import with link on WordPress

When I started tweaking the theme for WordPress, I started with css, especially the fonts. I wanted the fonts that mimic paper-like experience as much as possible, and although the goal post has shifted quite a lot since, the way I had done fonts on css were almost always the same.

On WordPress, you can change the stylesheet with its web-based text editor, aptly named “theme editor”. By using @import, you can use the Google Fonts or any other fonts without altering other files. For example, by announcing @import url('http://some.fonts.you.choose');, you can use the very same font declared in the URL and make adjustments in the same file.

Let us assume we are working with that statement and try to replace it for <link>. The same url can be preserved, but I do recommend double-checking with the service provider if any of it has changed since. In functions.php for the child theme you are currently using, add a code like this. Please don’t forget to replace the curly bracket is the existing URL you have used for @import statement:

//Google Fonts implementation
add_action('wp_head', 'google_fonts_api');
function google_fonts_api() {
	?>
	<link rel="preconnect" href="https://fonts.googleapis.com">
	<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
	<link href="{http://some.fonts.you.choose}" rel="stylesheet">
	<?php
}

@import statement on the css file will no longer be necessary. I would leave a comment somewhere in the file that function.php has the <link> to load the fonts. The code is simply implementing Google Fonts on header using WordPress hooks. As for the URL itself, I do want to emphasize give Google Fonts or your Fonts provider of choice another look. My link for Google Fonts was ancient enough that it was loading older version of APIs.

As I have discussed in App-to post, apparently it is against the norm to use @import, and rather uses <link> for performance gains. Google doesn’t specify which method is ‘better’, but I’ve seen some speculative posts that it is proof enough in Google’s language that the company is nudging toward <link> implementation. I can only attest to the fact that there is performance gains and <link> was much easier to work with.

Leave a comment