概要
wp_preload_resourcesフィルタは、プリロードするリソース(link要素)を表示する機能を持っています。これにより、ページの読み込み時間の最適化やユーザー体験の向上を図ることができます。このフィルタは、主に以下の場面で使われます。
- 外部スタイルシートのプリロード
- JavaScriptファイルのプリロード
- フォントリソースのプリロード
- 画像のプリロード
- CDNリソースのプリロード
- 特定のページテンプレート用のリソース選択
- プラグインによるカスタムリソースの追加
- グラフィックリソースのプリロード
構文
apply_filters( 'wp_preload_resources', $resources, $context );
パラメータ
$resources: プリロードするリソースの配列。$context: フィルタのコンテキスト。
戻り値
- プリロードするリソースの更新された配列。
関連する関数
wp_preload_resourcesの関連関数をこちらで確認できます
このフィルタを使用可能なバージョン
WordPress 5.5.0 以降
このフィルタが含まれるワードプレスのコアファイルのパス
wp-includes/general-template.php
この関数のアクションでの使用可能性
| アクション名 | 使用可能性 |
|---|---|
| mu_plugin_loaded | |
| registered_post_type | |
| plugins_loaded | |
| wp_roles_init | |
| setup_theme | |
| after_setup_theme | |
| set_current_user | |
| init | |
| register_sidebar | |
| wp_loaded | |
| send_headers | |
| parse_query | |
| pre_get_posts | |
| wp | |
| template_redirect | |
| get_header | |
| wp_head | 〇 |
サンプルコード
サンプルコード1: 外部CSSのプリロード
add_filter( 'wp_preload_resources', function( $resources ) {
$resources[] = '<link rel="preload" href="https://example.com/style.css" as="style">';
return $resources;
});
このサンプルコードは、外部CSSファイルをプリロードするためのlink要素を追加します。
サンプルコード2: JavaScriptファイルのプリロード
add_filter( 'wp_preload_resources', function( $resources ) {
$resources[] = '<link rel="preload" href="https://example.com/script.js" as="script">';
return $resources;
});
このコードは、指定したJavaScriptファイルをプリロードするlink要素を追加します。
サンプルコード3: フォントリソースのプリロード
add_filter( 'wp_preload_resources', function( $resources ) {
$resources[] = '<link rel="preload" href="https://fonts.googleapis.com/css?family=Roboto" as="style">';
return $resources;
});
このサンプルは、Googleフォントのリソースをプリロードするためのlink要素を追加します。
サンプルコード4: 画像リソースのプリロード
add_filter( 'wp_preload_resources', function( $resources ) {
$resources[] = '<link rel="preload" href="https://example.com/image.jpg" as="image">';
return $resources;
});
このコードは、特定の画像をプリロードするlink要素を追加します。
サンプルコード5: 特定のページでのみプリロード
add_filter( 'wp_preload_resources', function( $resources ) {
if ( is_page( 'about' ) ) {
$resources[] = '<link rel="preload" href="https://example.com/about-style.css" as="style">';
}
return $resources;
});
このサンプルコードは、「about」ページの際のみ、指定されたスタイルシートをプリロードするlink要素を追加します。