概要
wp_get_loading_attr_default
フィルタは、WordPressが画像やiframesなどのメディア要素において使用するデフォルトのloading
属性を取得するために利用されます。このフィルタを使用することで、デフォルトのloading
属性の値(lazy
やeager
)を変更することができます。具体的には、以下のような機能を実装する際によく使われます。
- ページのパフォーマンス向上
- ユーザーエクスペリエンスの改善
- SEO対策としての画像の遅延読み込み
- レスポンシブデザインにおけるメディア管理
- カスタムテーマやプラグインにおけるメディアの処理の調整
- 特定の条件に基づく読み込み属性の動的変更
- 画像の読み込みを制御するAPIの統合
- アナリティクスやトラッキングのためのカスタム設定
構文
add_filter('wp_get_loading_attr_default', 'custom_loading_attribute');
パラメータ
$loading
(string): デフォルトのloading
属性の値(例:lazy
,eager
)。$context
(string): 現在のコンテキスト。画像やiframeがどのように使用されているかに依存します。
戻り値
- (string): 修正された
loading
属性の値。
関連する関数
使用可能なバージョン
このフィルタはWordPress 5.5.0以降で使用可能です。
コアファイルのパス
wp-includes/media.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 – デフォルトのloading
属性をeager
に変更
function custom_loading_attribute($loading) {
return 'eager';
}
add_filter('wp_get_loading_attr_default', 'custom_loading_attribute');
このコードは、すべてのメディア要素においてデフォルトのloading
属性をeager
に変更します。
サンプルコード2 – 特定の条件に応じたloading
属性の変更
function conditional_loading_attribute($loading, $context) {
if ($context === 'example_context') {
return 'eager';
}
return $loading;
}
add_filter('wp_get_loading_attr_default', 'conditional_loading_attribute', 10, 2);
このコードは、特定のコンテキストでのみloading
属性をeager
に変更します。
サンプルコード3 – カスタムフィルタを使用する例
function custom_loading_with_filter($loading) {
return apply_filters('custom_filter_for_loading', $loading);
}
add_filter('wp_get_loading_attr_default', 'custom_loading_with_filter');
このコードは、外部フィルタを使用してloading
属性を変更することができます。
サンプルコード4 – クラスに基づく条件
function loading_attr_based_on_class($loading, $context) {
global $post;
if (has_class($post->ID, 'custom-class')) {
return 'eager';
}
return $loading;
}
add_filter('wp_get_loading_attr_default', 'loading_attr_based_on_class', 10, 2);
このコードは、特定のクラスが付与された投稿においてloading
属性をeager
に変更します。
サンプルコード5 – リアルタイムでのloading
属性変更
function real_time_loading_attribute($loading) {
if (is_page('about')) {
return 'lazy';
}
return $loading;
}
add_filter('wp_get_loading_attr_default', 'real_time_loading_attribute');
このコードは、特定のページ(この場合は「about」ページ)においてloading
属性をlazy
に変更します。
これらのサンプルコードはすべて、WordPressのフィルタを利用してデフォルトのloading
属性を変更する方法を示しています。