個人規模から中規模までのクライアントワークで使えるWordPressのカスタムを中心とした、Web制作に関することを書いてます。

wp_head() cleanerでwp_head()の出力する不要なコードを削除して整理する

wp_head()の出力する不要なコードを削除して整理する

wp_head()によって出力される、<head></head>タグ内を整理する。

デフォルトのソース

wp_head() が出力するデフォルトのタグがこちらです。

<head>
<meta charset="UTF-8">
<title>WP55検証用</title>
<meta name='robots' content='max-image-preview:large' />	<style>img:is([sizes="auto" i], [sizes^="auto," i]) { contain-intrinsic-size: 3000px 1500px }</style>	<link rel="alternate" type="application/rss+xml" title="WP55検証用 » フィード" href="https://example.com/?feed=rss2" />
<link rel="alternate" type="application/rss+xml" title="WP55検証用 » コメントフィード" href="https://example.com/?feed=comments-rss2" />
<script type="text/javascript">
/* <![CDATA[ */
window._wpemojiSettings = {"baseUrl":"https:\/\/s.w.org\/images\/core\/emoji\/15.1.0\/72x72\/","ext":".png","svgUrl":"https:\/\/s.w.org\/images\/core\/emoji\/15.1.0\/svg\/","svgExt":".svg","source":{"concatemoji":"https:\/\/example.com\/wp\/wp-includes\/js\/wp-emoji-release.min.js?ver=6.8"}};
/*! This file is auto-generated */
!function(i,n){var o,s,e;function c(e){try{var t={supportTests:e,timestamp:(new Date).valueOf()};sessionStorage.setItem(o,JSON.stringify(t))}catch(e){}}function p(e,t,n){e.clearRect(0,0,e.canvas.width,e.canvas.height),e.fillText(t,0,0);var t=new Uint32Array(e.getImageData(0,0,e.canvas.width,e.canvas.height).data),r=(e.clearRect(0,0,e.canvas.width,e.canvas.height),e.fillText(n,0,0),new Uint32Array(e.getImageData(0,0,e.canvas.width,e.canvas.height).data));return t.every(function(e,t){return e===r[t]})}function u(e,t,n){switch(t){case"flag":return n(e,"\ud83c\udff3\ufe0f\u200d\u26a7\ufe0f","\ud83c\udff3\ufe0f\u200b\u26a7\ufe0f")?!1:!n(e,"\ud83c\uddfa\ud83c\uddf3","\ud83c\uddfa\u200b\ud83c\uddf3")&&!n(e,"\ud83c\udff4\udb40\udc67\udb40\udc62\udb40\udc65\udb40\udc6e\udb40\udc67\udb40\udc7f","\ud83c\udff4\u200b\udb40\udc67\u200b\udb40\udc62\u200b\udb40\udc65\u200b\udb40\udc6e\u200b\udb40\udc67\u200b\udb40\udc7f");case"emoji":return!n(e,"\ud83d\udc26\u200d\ud83d\udd25","\ud83d\udc26\u200b\ud83d\udd25")}return!1}function f(e,t,n){var r="undefined"!=typeof WorkerGlobalScope&&self instanceof WorkerGlobalScope?new OffscreenCanvas(300,150):i.createElement("canvas"),a=r.getContext("2d",{willReadFrequently:!0}),o=(a.textBaseline="top",a.font="600 32px Arial",{});return e.forEach(function(e){o[e]=t(a,e,n)}),o}function t(e){var t=i.createElement("script");t.src=e,t.defer=!0,i.head.appendChild(t)}"undefined"!=typeof Promise&&(o="wpEmojiSettingsSupports",s=["flag","emoji"],n.supports={everything:!0,everythingExceptFlag:!0},e=new Promise(function(e){i.addEventListener("DOMContentLoaded",e,{once:!0})}),new Promise(function(t){var n=function(){try{var e=JSON.parse(sessionStorage.getItem(o));if("object"==typeof e&&"number"==typeof e.timestamp&&(new Date).valueOf()<e.timestamp+604800&&"object"==typeof e.supportTests)return e.supportTests}catch(e){}return null}();if(!n){if("undefined"!=typeof Worker&&"undefined"!=typeof OffscreenCanvas&&"undefined"!=typeof URL&&URL.createObjectURL&&"undefined"!=typeof Blob)try{var e="postMessage("+f.toString()+"("+[JSON.stringify(s),u.toString(),p.toString()].join(",")+"));",r=new Blob([e],{type:"text/javascript"}),a=new Worker(URL.createObjectURL(r),{name:"wpTestEmojiSupports"});return void(a.onmessage=function(e){c(n=e.data),a.terminate(),t(n)})}catch(e){}c(n=f(s,u,p))}t(n)}).then(function(e){for(var t in e)n.supports[t]=e[t],n.supports.everything=n.supports.everything&&n.supports[t],"flag"!==t&&(n.supports.everythingExceptFlag=n.supports.everythingExceptFlag&&n.supports[t]);n.supports.everythingExceptFlag=n.supports.everythingExceptFlag&&!n.supports.flag,n.DOMReady=!1,n.readyCallback=function(){n.DOMReady=!0}}).then(function(){return e}).then(function(){var e;n.supports.everything||(n.readyCallback(),(e=n.source||{}).concatemoji?t(e.concatemoji):e.wpemoji&&e.twemoji&&(t(e.twemoji),t(e.wpemoji)))}))}((window,document),window._wpemojiSettings);
/* ]]> */
</script>
<style id='wp-emoji-styles-inline-css' type='text/css'>	img.wp-smiley, img.emoji {	display: inline !important;	border: none !important;	box-shadow: none !important;	height: 1em !important;	width: 1em !important;	margin: 0 0.07em !important;	vertical-align: -0.1em !important;	background: none !important;	padding: 0 !important;	}
</style>
〜〜〜 省略 〜〜〜
<link rel="https://api.w.org/" href="https://example.com/index.php?rest_route=/" /><link rel="EditURI" type="application/rsd+xml" title="RSD" href="https://example.com/wp/xmlrpc.php?rsd" />
<meta name="generator" content="WordPress 6.8" />
</head>

プラグインのインストール

同様の機能を持つプラグインは多数ありますが、今回は最新版であるWP6.8対応・日本語対応している wp_head() cleaner を使います。

プラグインのインストール方法

WordPressのプラグインをインストールする3つの方法 WordPressのプラグインをインストールする3つの方法

使い方

ダッシュボードの、[ツール] – [wp_head() cleaner] と進み、停止したい項目にチェックを入れて保存します。
日本語化されてるので分かりやすいですね〜

設定できる項目

  • Really Simple Discovery
  • Windows Live Writer
  • WordPress の generator メタタグ
  • 記事の関連リンク – Start
  • 記事の関連リンク – Index
  • 投稿の関連リンク – prev と next
  • 投稿の shortlink
  • canonical リンク
  • 投稿とコメント用フィード
  • ほかのフィード、カテゴリーフィードなど
  • Emoji 用スクリプト
  • Emoji 用スタイル
  • REST API
  • oEmbed タグ
  • oEmbed スクリプト
  • リソースの示唆
  • 検索ロボット向け画像プレビュー

全て停止した場合のソース

スッキリ!
〜〜〜 省略 〜〜〜 の箇所は block-library 関連のCSSが入ります。

<head>
<meta charset="UTF-8">
<title>WP55検証用</title>
<style>img:is([sizes="auto" i], [sizes^="auto," i]) { contain-intrinsic-size: 3000px 1500px }</style>
〜〜〜 省略 〜〜〜
</head>

functions.php に直接書く方法 *非推奨

functions.php の直接書く方法は推奨されていません。
これを使う場合、独自プラグイン化する事をお勧めします。

/* ----------------------------------------------------------------------
HEAD Clean
---------------------------------------------------------------------- */
function remove_dns_prefetch( $hints, $relation_type ) {	if ( 'dns-prefetch' === $relation_type ) {	return array_diff( wp_dependencies_unique_hosts(), $hints );	}	return $hints;
}
add_filter( 'wp_resource_hints', 'remove_dns_prefetch', 10, 2 );
remove_action( 'wp_head', 'feed_links_extra', 3 );
/* STOP EMOJI */
function remove_emoji() {	remove_action( 'wp_head', 'print_emoji_detection_script', 7 );	remove_action( 'admin_print_scripts', 'print_emoji_detection_script' );	remove_action( 'wp_print_styles', 'print_emoji_styles' );	remove_action( 'admin_print_styles', 'print_emoji_styles' );	remove_filter( 'the_content_feed', 'wp_staticize_emoji' );	remove_filter( 'comment_text_rss', 'wp_staticize_emoji' );	remove_filter( 'wp_mail', 'wp_staticize_emoji_for_email' );
}
add_action( 'init', 'remove_emoji' );
/* REST API */
// 除外するプラグインを設定
function deny_restapi_except_plugins( $result, $wp_rest_server, $request ){	$namespaces = $request->get_route();	// oembed	if( strpos( $namespaces, 'oembed/' ) === 1 ) {	return $result;	}	// Jetpack	if( strpos( $namespaces, 'jetpack/' ) === 1 ) {	return $result;	}	// BlockEditor	if ( current_user_can( 'edit_posts' ) ) {	return $result;	}	return new WP_Error( 'rest_disabled', __( 'The REST API on this site has been disabled.' ), array( 'status' => rest_authorization_required_code() ) );
}
add_filter( 'rest_pre_dispatch', 'deny_restapi_except_plugins', 10, 3 );
remove_action( 'wp_head', 'rsd_link' );
remove_action( 'wp_head', 'wlwmanifest_link' );
remove_action( 'wp_head', 'adjacent_posts_rel_link_wp_head' );
remove_action( 'wp_head', 'wp_generator' );
remove_action( 'wp_head', 'rel_canonical' );
remove_action( 'wp_head', 'wp_shortlink_wp_head' );
remove_action( 'wp_head', 'wp_oembed_add_discovery_links' );
remove_action( 'wp_head', 'wp_oembed_add_host_js' );

注意点

wp_head() クリーン系のプラグインは多数ありますが、プラグインのメンテナンスがされてないものも多数あるため注意が必要です。また、こんかい紹介したプラグインもいずれメンテナンスされなくなる可能性もあるので併せて注意が必要になります。

メンテナンスされていないと、将来的に wp_head() に挿入されるタグに対応出来ない事になります。

検証環境

サーバー:heteml / テーマ:検証用のオリジナルテーマ
WordPress 6.8 / PHP 8 / MySQL 8
今回のプラグイン:wp_head() cleaner Ver.2.0.8