概要
wp_omit_loading_attr_threshold
フィルタは、画像やiframeのloading
属性を決定するためのしきい値を取得するために使用されます。このフィルタは、特定の条件に応じて、どのメディア要素に対してloading
属性を省略するかを制御できます。主にパフォーマンス向上やSEO対策のためによく使われます。
よく使われる機能
- 画像の遅延読み込みを制御する
- iframeの読み込みの最適化
- ページパフォーマンスの向上
- SEO対策を兼ねたユーザーエクスペリエンスの改善
- スクロールに応じて画像を読み込む
- バナー広告の読み込みコントロール
- レスポンシブデザインの最適化
- メディアライブラリからの画像表示の最適化
構文
add_filter( 'wp_omit_loading_attr_threshold', 'custom_omit_loading_attr_threshold' );
function custom_omit_loading_attr_threshold( $threshold ) {
// カスタムロジックを実装
return $threshold;
}
パラメータ
$threshold
(int) – 画像や要素にloading
属性を適用するかどうかのしきい値。
戻り値
- (int) – 設定したしきい値。
関連する関数
wp_omit_loading_attr_threshold
使用可能なバージョン
WordPress 5.5.x以上で使用可能。
コアファイルのパス
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
add_filter( 'wp_omit_loading_attr_threshold', function( $threshold ) {
return 10; // 10画像以上でloading属性を省略
});
このコードは、10枚以上の画像がある場合にloading
属性を省略するしきい値を設定します。
サンプルコード 2
add_filter( 'wp_omit_loading_attr_threshold', function( $threshold ) {
return is_single() ? 5 : $threshold; // シングルページでは5枚以上で省略
});
このコードは、シングルページでは5枚以上の画像に対してloading
属性を省略します。
サンプルコード 3
add_filter( 'wp_omit_loading_attr_threshold', function( $threshold ) {
if ( is_home() ) {
return 8; // ホームページの場合は8枚以上で省略
}
return $threshold;
});
このコードは、ホームページで8枚以上の画像に対してloading
属性を省略する設定です。
サンプルコード 4
add_filter( 'wp_omit_loading_attr_threshold', function( $threshold ) {
return 15; // デフォルトのしきい値を15に設定
});
このコードは、loading
属性を省略するためのデフォルトのしきい値を15に設定します。
サンプルコード 5
add_filter( 'wp_omit_loading_attr_threshold', function( $threshold ) {
return $threshold > 20 ? 20 : $threshold; // 最大しきい値を20に制限
});
このコードは、しきい値が20を超えないように制限します。
著作権フリーのサンプルコードの出典はリソースとして確認や修正が必要な場合がありますが、上記のコードは一般的なパターンを示すものです。公式の WordPress Codex や開発文書も参照をおすすめします。