Voulez-vous ajouter les polices de caractères Google dans votre thème WordPress ?
Les polices Google vous permettent d’utiliser facilement de belles polices web sur votre site WordPress. Vous pouvez les utiliser pour améliorer la typographie, l’expérience utilisateur et l’esthétique de votre site.
Cet article vous affichera comment ajouter correctement les polices web de Google aux thèmes WordPress.
Voici un bref aperçu des sujets que nous aborderons dans ce guide.
- Finding the Best Google Fonts for Your WordPress Theme
- Method 1. Adding Google Fonts to Your Theme Using Plugin
- Method 2. Adding Google Web Fonts to Your Theme's Header
- Method 3. Add Google Fonts in Theme's Stylesheet
- Method 4. Properly Enqueue Google Fonts in WordPress
- Bonus Section: How Web Fonts Affect WordPress Speed
Trouver les meilleures polices Google pour votre thème WordPress
La première chose à faire est de trouver les polices Google qui vous plaisent. Il vous suffit de vous rendre sur le site de Google Fonts et de parcourir la bibliothèque.
Lorsque vous trouvez une police sûre pour le web qui vous plaît, cliquez dessus pour afficher les différents styles disponibles.
Vous pouvez sélectionner les styles que vous souhaitez utiliser sur votre site.
Cliquez ensuite sur le bouton « Voir les familles sélectionnées », qui ouvre une colonne latérale.
À partir de cette page, vous consulterez les instructions d’utilisation dans la section « Utilisation sur le web ».
Vous verrez qu’il y a deux onglets différents pour ajouter la police à votre site
La première est la méthode Link, qui est la méthode standard recommandée pour ajouter des polices web.
Le deuxième onglet utilise la méthode CSS @import qui vous permet de charger les polices via votre feuille de style CSS.
Nous allons vous afficher comment utiliser chacune de ces méthodes et quels sont leurs avantages et leurs inconvénients.
Note : Pour certaines de ces méthodes, vous devrez modifier les fichiers de votre thème WordPress. Vous pouvez le faire en vous connectant à votre site à l’aide d’un client FTP ou de l’application Gestionnaire de fichiers sous le panneau de contrôle de votre hébergeur.
Une fois connecté, vous devez visiter le dossier /wp-content/themes/Your-Theme-Name/
. De là, vous trouverez des fichiers de thème que vous devrez peut-être modifier pour ce tutoriel.
Pour plus de détails, consultez notre tutoriel sur la manière de copier et coller des extraits de code dans WordPress.
Méthode 1. Ajouter les polices Google Ads à votre thème à l’aide d’une extension
Pour cette méthode, nous utiliserons une extension WordPress pour charger les polices Google.
Tout d’abord, vous devez installer et activer l’extension Fonts. Pour plus de détails, consultez notre guide étape par étape sur l’installation d’une extension WordPress.
Une fois activé, vous devez visiter la page Apparence » Personnaliser pour lancer le personnalisateur de thème. À partir de là, vous verrez le nouvel onglet Fonts Plugin.
En cliquant dessus, vous afficherez les options d’extension.
Vous pouvez choisir d’utiliser les polices Google pour différentes parties de votre site.
Vous pouvez également choisir de charger une police pour votre thème WordPress.
Il suffit de passer à l’onglet Réglages avancés » Charger les polices uniquement « .
À partir de là, vous pouvez choisir les polices Google que vous souhaitez charger pour votre thème WordPress.
Il suffit de taper le nom de la police et de la sélectionner.
Une fois que vous avez terminé, n’oubliez pas de cliquer sur le bouton Publier pour enregistrer vos modifications.
Si vous avez utilisé les fonctionnalités avancées de l’extension pour assigner des polices à différentes parties de votre site, celles-ci fonctionneront automatiquement.
En revanche, si vous avez choisi de charger uniquement des polices, vous devrez ajouter des règles CSS personnalisées pour celles-ci. Par exemple, voici comment charger une police pour l’élément paragraphe dans l’ensemble de votre site.
p {
font-family: 'Open Sans', sans-serif;
}
Méthode 2. Ajout de Google Web Fonts à l’en-tête de votre thème
Cette méthode est la plus simple pour ajouter des polices Google directement à votre thème WordPress.
Il suffit de modifier le fichier header.php de votre thème WordPress ou de votre thème enfant. Ensuite, copiez et collez le code Link avant le code de lien de la feuille de style de votre thème WordPress.
Voici à quoi cela ressemblerait :
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Open+Sans:wght@400;800&display=swap" rel="stylesheet">
<link rel="stylesheet" type="text/css" href="YOUR THEME STYLESHEET" media="screen">
Fondamentalement, l’objectif est de placer la demande de polices le plus tôt possible. Cela permet au navigateur de l’utilisateur/utilisatrice de télécharger les polices avant de rendre la page.
Une fois que vous avez fait cela, vous pouvez utiliser la police dans le fichier CSS de votre thème :
h1 {
font-family: 'Open Sans', sans- serif;
}
Méthode 3. Ajouter les polices Google dans la feuille de style du thème
Pour cette méthode, nous allons importer le CSS de la police dans le fichier CSS principal de notre thème WordPress.
Modifiez simplement le fichier style.css dans le dossier racine de votre thème WordPress et ajoutez le code de l’onglet « @import » en haut du fichier CSS.
@import url('https://fonts.googleapis.com/css2?family=Open+Sans:wght@400;800&display=swap');
Voici à quoi cela ressemble dans le fichier style.css de notre site de démonstration.
Important : Veillez à ajouter la ligne @import au début de votre fichier CSS.
Méthode 4. Enqueuter correctement les polices de Google dans WordPress
Les deux premières méthodes que nous avons mentionnées précédemment nécessitent d’ajouter directement des polices en modifiant les fichiers de votre thème WordPress.
Cela fonctionne bien si vous utilisez un thème enfant pour effectuer toutes vos modifications.
En revanche, si vous apportez ces modifications au thème principal, elles seront perdues lors de la prochaine mise à jour du thème.
Une solution plus simple consiste à ajouter un code programmatique qui charge automatiquement les polices Google pour que votre thème WordPress puisse les utiliser.
Pour cela, vous devez ajouter un extrait de code personnalisé à un plugin spécifique au site ou en utilisant une extension de code personnalisé. Pour plus de détails, consultez notre tutoriel sur la façon d’ajouter du code personnalisé dans WordPress.
Il suffit d’ajouter l’extrait de code suivant à votre site WordPress.
function wpb_add_google_fonts() {
wp_enqueue_style( 'wpb-google-fonts', 'https://fonts.googleapis.com/css?family=Open+Sans:300italic,400italic,700italic,400,700,300', false );
}
add_action( 'wp_enqueue_scripts', 'wpb_add_google_fonts' );
Note : N’oubliez pas de remplacer l’URL par l’URL des polices Google que vous souhaitez ajouter.
C’est tout, WordPress utilisera désormais la méthode Link pour récupérer automatiquement les polices Google que vous avez ajoutées.
Vous pouvez le confirmer en consultant le code source de votre site, vous y verrez votre feuille de style de Google fonts ajoutée dans la section pied de page de votre site.
Section bonus : Comment les polices de caractères affectent la vitesse de WordPress
Les polices de Google se chargent très rapidement car elles sont servies par l’énorme réseau CDN de Google, dont les serveurs sont répartis dans le monde entier.
Comme ces polices sont utilisées par des millions de sites, il y a de fortes chances que les utilisateurs/utilisatrices les aient déjà stockées dans la mise en cache de leur navigateur.
Cela réduit leur impact sur la vitesse de votre site. Vous pouvez encore réduire cet impact en utilisant uniquement une ou deux polices web dans votre conception.
Pour plus d’astuces, consultez notre guide complet sur les performances et la vitesse de WordPress pour les débutants.
Nous espérons que ce guide vous a aidé à apprendre comment ajouter facilement Google Web Fonts à votre thème WordPress. Vous pouvez également consulter notre guide sur la façon de créer un thème WordPress personnalisé à partir de zéro sans codage et notre liste des meilleurs services d’hébergement de sites Web gratuits.
Si vous avez aimé cet article, veuillez alors vous abonner à notre chaîne YouTube pour obtenir des tutoriels vidéo sur WordPress. Vous pouvez également nous trouver sur Twitter et Facebook.
Armando
I noticed that this video/instructions are dated 2015 and the screenshots, etc. are different. When I tried to embed the Google Fonts code in my header.php file as shown, it threw an error. So I’m thinking maybe this tutorial needs to be updated? Not sure, but… Thanks.
WPBeginner Support
Thank you for your feedback, we’ll be sure to take a look into updating this article when able.
Administrateur
Wout
Thanks for the article! Please replace http: in fonts.googleapis.com/css… with https: in the function to enqueue Google Fonts to enable an encrypted link to googleapis.com…
WPBeginner Support
Thanks for pointing this out, we will be sure to update the links as soon as we are able
Administrateur
Sofia
I’m pretty sure it’s 2017 why we even have to learn all this : »((
charles
Is this still the right way to do it?
Renee
I got the font to show up but can’t figure out how to get it bold.
Here’s an example of what i did in the css
font-family: »Open Sans », sans-serif;
font-weight:bold;
in the link i added to my header.php i added this:
i tried subbing 700 for bold but no luck…
any ideas?
thanks in advance
Isaac Anderson
Make sure you check your desired font-weights on Google fonts after selecting them in the « customize » tab.
Louis
Works perfect! Thx.
josh
Huh? Wtf does any of this mean? How do I make it so that I can just add a google font in my post or page?
Shubham Kumar
What do you think about importing Google web Fonts using JavaScript asynchronously as mentioned over here :
Thanks
Shubham
Jordan
One quick question – I looked up the code reference for wp_enqueue_style(). Its first argument is a string that denotes the name of the stylesheet. In your example, you use ‘wpb-google-fonts’ for the first argument. How can I tell what to put here for my site?
pete rome
where do I paste stuff in the header exactly? always see that but people never explain exactly where it is.
Carla DeLauder
What does ‘false’ do in this function? Other enqueued functions don’t include it.
Thank you.
Kev
that’s the argument for header or footer. Since best practice is to put [almost] all scripts in the header it defaults to ‘true’ => footer, whereas ‘false’ would mean the NOT in the footer, but in the header instead.
Unfortunately, font scripts stop everything else from loading, so putting them in the header sucks a litlte bit, which is why this article talks about making sure you’re only including the fonts you’ll actually use. On the flip side, putting them in the footer can cause default fonts like arial to load momentarily on your screen during painting until the webfont gets loaded. It’s a horrible caveat, but it is what it is.
A practice I’m working into my workflow is to conditionally load fonts based on their usage in the site. For example, maybe « bold » is only used in h2’s and h3’s in blog post templates (single.php), then I’ll write a conditional enqueue for the bold script to only be enqueued when on single.php template.
Hope that helps.
Kev
Also, to note.
By « bold » above, I meant a specific bold version of a font family. <= just a head's up.
Kenneth John Odle
As of WordPress 3.3, wp_print_styles is deprecated.
Bram
Yeah, you should update this article.
WPBeginner Support
Updated.
Administrateur
WPBeginner Support
We have updated the article, it now shows how to add Google fonts using the proper
wp_enqueue_style
function and wp_enqueue_scripts action hook.Administrateur
isak
How do you enque two font families via functions.php?
April
I’m using the Punch Fonts plugin to add google fonts but I am not sure how to just get only heading 1 for the desired font. I don’t need this font for headings 2-6 so I only want to use the google font for heading one. How do I write that in the parameter?
Currently I’m using: Oleo+Script+Swash+Caps:400
Melissa
Well, if anyone is stuck, there is also this plugin called Easy Google Fonts. Very helpful.
Melissa
Hello,
I have tried all three methods but neither of them took effect completely. It seems that it only applies to certain elements and not to others that I specified with that font in the style sheet
When I use the Element Inspector for the element where my Google Font is not applied, this is what I see:
#site-title {
font-family: \’Questrial\’, Helvetica, Arial, sans-serif;
What do these mean \\ around my font? I mean, it looks like it is indicating an error but I can’t figure out what I am doing wrong? What could it be? Some code overriding mine, with higher priority? but where? how? Arghhhh it’s driving me nuts
Ali Sajjad
Dear Editorial, i want to add all google web fonts in this site, and then want to use in my means,
but i dont want to use too many links in header file. any other way?
WPBeginner Support
Only add the fonts that you want to use.
Administrateur
Anurag
So, I have got a blog ( http://www.goingtechy.com/ ). The problem I am having is that I want to optimize css delivery of the Google font that my site uses already. So, the site already have Google fonts. How can I optimize it?
Samantha
Thank you so much for this post! For someone who has no formal html/css training, I was impressed with the simplicity of this post.
Tanisha
So easy and go it to work perfectly. Thanks for this.
Greg
Hi there,
Using Genesis and the Parallax Pro theme…
But a newb to things like php etc
I added this code to the fuctions.php file as you insctructed:
add_action( ‘genesis_meta’, ‘wpb_add_google_fonts’, 5);
function wpb_add_google_fonts() {
echo »;
}
The headers that use the font above remain unchanged.
Questions:
1. Am I right in assuming that the code above is the only thing that I add?
2. Where exactly should the code be added – at the beginning or end of fuctions.php?
2. Is there anything missing from the code?
3. Should I be adding something to the style.css file?
Appreciate your help
Regards
Greg
WPBeginner Support
Greg, seems alright to us. We think WordPress probably omitted the part from your code where you echoed font link. Yes you will need to use CSS to set style rules for selectors where you want to use your Google font.
Administrateur
Tony Porto
None of the above is good enough, we all know « wp_enqueue_style( ‘google-font’) » is the « technically correct way to call a script, but in this case your <header will end up like this;
FONT 1:
FONT 2:
FONT 3:
FONT 4:
No Good, it needs to be like this:
Akmal
Where should i paste the above code? I could not find the last line of code anywhere in my header.php file? Can you please tell me step-wise?
Thanks.
WPBeginner Support
In your header.php file you will find
</head>
you can paste this code any where before this tag.Administrateur
Sarah
Tried re-typing the following, and still nothing is changing;
/* Import Fonts
———————————————————— */
add_action( ‘genesis_meta’, ‘wpb_add_google_fonts’, 5);
function wpb_add_google_fonts () {
echo ‘’;
}
/* Defaults
It worked the first time. I’m so confused!
Thanks for your help.
Sarah
Hi,
I was so proud of myself for copying the code and changing the font which, I found too large for my site. When I tried to change it to something else, I must have mixed something up, and only one font style continues to show, even when I play about with the codes. Feeling like a dunce now – I don’t talk tech. Can anyone help me? I’ve done it with and without the numbers in case they’re not actually part of it. Thanks. This is the latest that I entered…..
/* Import Fonts
———————————————————— */
1 add_action( ‘genesis_meta’, ‘wpb_add_google_fonts’, 5);
2
3 function wpb_add_google_fonts() {
4 echo »;
5 }
/* Defaults
———————————————————— */
WPBeginner Support
we hope you did not enter the numbers with the code Or did you?
Administrateur
Sarah
No numbers, but I am missing something this time around. This is exactly what I have in my table;
add_action( ‘genesis_meta’, ‘wpb_add_google_fonts’, 5);
function wpb_add_google_fonts() {
echo »;
}
Sarah
It seems the code worked…..on one computer. It hasn’t taken on two others that I use.
Can you please suggest why that might be the case?
Thanks so much
Karissa Skirmont
How can you use multiple Google Fonts in the functions.php ?
I had this:
But the Dancing Script wasn’t showing up font on my second computer or iPhone or tablet.
I removed the Open Sans and it started working.
WPBeginner Support
@Karissa, the first argument in wp_enqueue_style function is the handle for the style script you are loading. Try this code instead:
1-click Use in WordPress
Administrateur
Karissa Skirmont
Nevermind, I figured out that I needed to use a link like this:
‘//fonts.googleapis.com/css?family=Euphoria+Script|Rouge+Script|Montez|Federo|Great+Vibes|Clicker+Script|Dancing+Script:400,700|Satisfy|Ruthie|Rochester|Open+Sans|Open+Sans+Condensed:300’
Karissa Skirmont
Ahh I see, I replied above before refreshing the page and seeing your reply.
By using the link Google gives when you have multiple fonts selected, it produces it like that and you can more easily try out different fonts live on site.
Chaitanya
Thank you so much!! Whenever I need any WordPress help, I come directly to wpbeginner as I know I would find a best solution here. You guys don’t know how much you have helped beginners like me, Appreciate you support
Long Live WPBeginner…
Cheers,
Chaitanya
Jenny
Meh, I like using the import. Less work for me ’cause I’m lazy~
pete rome
yeah way too much work on each method here and there shouldn’t be a need to add anything to the style sheet find a plugin
Jimmy Reynolds
A you mean the nerd way
mzilverberg
Something I missed here were the conditional comments to make Google’s webfonts work in IE8 and below if you request more than one font weight. For example:
<link href=”http://fonts.googleapis.com/css?family=Cabin:400,700″ rel=”stylesheet” type=”text/css” />
That’s why I created a function for loading fonts: https://github.com/mzilverberg/LoadGoogleWebfonts
My script also places the appropriate fallback urls within a conditional comment.
With a few lines of code you could also make this work in functions.php in your Wordpress theme.
Greg
What about adding Google Fonts to the admin side?
Editorial Staff
Why would you want to add Google Fonts to the admin side?
Administrateur
Bruce Smith
To maintain WYSIWYG in the admin content editor. So that I see the same font face in the admin editor as on my web site.
Dan Merhar
I was actually wondering how to do the same thing (and this is the first result that popped up on Google).
I know plug-ins exist to add Google Webfonts functionality to the WYSIWYG editor, but they bog it down like crazy. I’m going to look into it further and see if there’s an easy way to add a font or two.
Marleen
Thanx a lot for sharing, I’m really happy with this. I’m a Genesis user and started using @import because it’s alraedy being done in the stylesheet. Feel much better about this solution.
Happy 2013!
jeff
In your code do I replace « YOUR THEME STYLESHEET » with something??
mine is STYLE.CSS, or does it need to be a URL ??
thanks,
Jeff
Editorial Staff
Yes, you need to insert your theme’s style.css path there.
Administrateur
Charles
This is what I use…..
Add this to your theme’s functions.php file:
What do you think about this?
Chris Reynolds
This is the CORRECT way to add Google fonts. Always use wp_register_style/wp_enqueue_style
David
Better still add a conditional comment to serve the fonts separately for IE 7 and 8:
From here:
http://www.smashingmagazine.com/2012/07/11/avoiding-faux-weights-styles-google-web-fonts/
Bryan Nickson
Nice tuts. I had wanted something like this..Kudos!!
Peter
What about the JS option, is that a faster option Or the one is the better?. Thanks
Editorial Staff
The method in this one is by far the most recommended one.
Administrateur
QLStudio
In your answer you don’t enqueue the css – is that really the best way to add it?
Chris
Great article! I think it would be pretty cool if wordpress, by default, had Google Fonts included into it, but this seems easy enough. Thanks for explaining!
Editorial Staff
Google Fonts are great, but not everyone uses it (considering the amount of folks who use WordPress). WordPress has a 95% rule. If the feature would not satisfy 95% of the audience, then it is usually falls in the plugins category. However, sometimes exceptions are made. We can assure you that the Core WP team, will not make this into an exception though
Administrateur
Aaron Crow
You rock man! Just what I was looking for! Thanks for putting up this post… I searched forever trying to find something about adding this to my theme. Glad I stumbled across your page.
Anderson Curry
Great post and even if their is a plug-in to do this, it’s always better to learn the non – plugin way also.
Brad
So obviously you dont accept using the several Google font plugins. I am going to have to revisit my css files in that case.
sadhu
i dont understand the second part which is adding font to the genesis add action thing.. is that another method to add in google web font?
and i know we dont have to incld all styles of the font, but the recommended method, which is http://fonts.googleapis.com/css?family=Lora|Oswald
just for instance, what if i only want bold style for lora and light style for oswald, then how to combine the font styles?
thanks
Editorial Staff
The second part is for Genesis Users ONLY. If you are not using the Genesis Theme Framework, then you don’t need that part. To combine styles like you want, here is how you do it:
http://fonts.googleapis.com/css?family=Oswald:300|Lora:700
Administrateur
Anton
What should I do if I want to use @font-face in Genesis Framework like you showed here with the Google Webfonts, are there any solution for that.
I’ve been searching all day since my fonts loads incredibly slow!
Cheers
Gautam Doddamani
great tutorial…i actually use the wp google fonts plugin…would you recommend that plugin or doing the manual way as described above..which is efficient performance wise?
Editorial Staff
Haven’t tried that plugin. But we almost try to avoid plugins of that sort because it can be done easier with theme files.
Administrateur
Gautam Doddamani
sweet…thanks will edit my theme instead of using a plugin
Pippin
Avoiding the google fonts plugin because it is a plugin is not a good reason at all. Using the plugin actually provides you with much more flexibility than including it in your theme, especially if you ever choose to change themes.
Editorial Staff
As far as I’m concerned, fonts in most cases are considered stylistic elements thus theme based, and they usually change when you switch to a different theme.
Siddanth Adiga
Superb post I was looking for this only i was trying my hands with css and fontface .I ll try this one too thanks
Konstantin Kovshenin
The « Right » way would be to use the wp_enqueue_style function Here’s some more thoughts: http://kovshenin.com/2012/on-wordpress-theme-frameworks/
Editorial Staff
Konstantin, I totally agree with you. wp_enqueue_style function should always be used. That is what I tried doing first as suggested by Nathan Rice, in StudioPress’s article about Google Fonts. Except Google clearly states, that the font styles should be loaded before anything else. Using wp_enqueue_style and then printing them using wp_print_styles, this was printing the item after the main stylesheet was already loaded. That was the reason why I had to hook into genesis_meta() hook. Anyways, totally agree with your thoughts on your article.
Administrateur
Japh
I’m a little late to this, but I wanted to mention that you could still use
wp_enqueue_style
, just set the priority higher so that they are loaded firstBob R
Great tutorial. One observation though: first image in the article was meant to show the @import tab, wasn’t it?
Editorial Staff
No it wasn’t suppose to show that.
Administrateur