wp_iframe_tag_add_loading_attr()


WordPressのwp_iframe_tag_add_loading_attr()関数は、iframeタグにloading="lazy"属性を追加するために使用されます。これにより、ページの読み込みパフォーマンスが向上します。

構文

wp_iframe_tag_add_loading_attr( string $iframe, string $context );

引数の説明:

  • $iframe(string) — iframeタグのHTMLコード。
  • $context(string) — iframeが使用されているコンテキスト(例: ‘embed’, ‘content’)。

例1: 基本的な使用例

iframeタグにloading="lazy"属性を追加します。

echo wp_iframe_tag_add_loading_attr( '<iframe src="https://example.com"></iframe>', 'embed' );

例2: コンテンツ内のiframeに属性を追加

投稿コンテンツ内のiframeにloading="lazy"属性を追加します。

add_filter( 'the_content', function( $content ) { return wp_iframe_tag_add_loading_attr( $content, 'content' ); } );

例3: カスタムiframeタグに属性を追加

カスタムiframeタグにloading="lazy"属性を追加します。

$custom_iframe = '<iframe src="https://custom.com"></iframe>'; echo wp_iframe_tag_add_loading_attr( $custom_iframe, 'custom' );

例4: 複数のiframeタグに属性を追加

複数のiframeタグを含むHTMLにloading="lazy"属性を追加します。

$multiple_iframes = '<iframe src="https://example1.com"></iframe><iframe src="https://example2.com"></iframe>'; echo wp_iframe_tag_add_loading_attr( $multiple_iframes, 'content' );

例5: 特定のコンテキストでのみ属性を追加

特定のコンテキスト(例: ‘embed’)でのみloading="lazy"属性を追加します。

if ( $context === 'embed' ) { echo wp_iframe_tag_add_loading_attr( $iframe, $context ); }

例6: 属性が既にある場合の処理

既にloading属性がある場合、上書きせずにそのまま返します。

if ( strpos( $iframe, 'loading=' ) === false ) { echo wp_iframe_tag_add_loading_attr( $iframe, $context ); }

例7: フィルターフックを使用した属性追加

フィルターフックを使用して、すべてのiframeタグにloading="lazy"属性を追加します。

add_filter( 'wp_iframe_tag_add_loading_attr', function( $iframe, $context ) { return wp_iframe_tag_add_loading_attr( $iframe, $context ); }, 10, 2 );

注意点

  • この関数はWordPress 5.5以降で利用可能です。
  • iframeタグが正しくフォーマットされていない場合、予期しない動作が発生する可能性があります。
  • 既にloading属性が存在する場合、この関数はその属性を上書きしません。

関連機能: