preconnect対応版。
どういうことか
こういうのがあるとする。
<head>
⋮
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons|Material+Icons+Outlined|Material+Icons+Two+Tone">
<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Noto+Sans+JP:wght@100..900&family=Noto+Serif+JP:wght@200..900&display=swap">
⋮
</head>header.phpに直書きしてもいいんだけど、色々書いていくと邪魔くさかったりするのでfunctions.phpで出力できるようにしたい。
言い換えれば、<?php wp_head(); ?>で出力する中に入れ込みたい。
やっていく
add_action('wp_enqueue_scripts', 'add_headFiles');
function add_headFiles() {
if(is_admin()) return;
wp_enqueue_style('fontMaterialIcons', 'https://fonts.googleapis.com/icon?family=Material+Icons|Material+Icons+Outlined|Material+Icons+Two+Tone', array());
wp_enqueue_style('fontGoogle', 'https://fonts.googleapis.com/css2?family=Noto+Sans+JP:wght@100..900&family=Noto+Serif+JP:wght@200..900&family=Jost:ital,wght@0,100..900;1,100..900&display=swap', array());
}
add_filter('style_loader_tag', 'add_headPreconnect', 10, 4);
function add_headPreconnect($tag, $handle, $href, $media) {
if ('fontMaterialIcons' === $handle || 'fontGoogle' === $handle) {
$preconnect = '<link rel="preconnect" href="https://fonts.googleapis.com">' . "\n";
$preconnect .= '<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>' . "\n";
static $done = false;
if (!$done) {
$done = true;
return $preconnect . $tag;
}
}
return $tag;
}wp_enqueue_style()でまとめることはできないので、それに関連して挿入する感じになる。

コメント