wp_style_add_data()


関数WordPresswp_style_add_data()は、登録されたスタイルシートにメタデータを追加するために使用されます。この関数は、スクリプトの依存関係を管理したり、条件付きでスタイルを読み込む場合に便利です。

構文

wp_style_add_data( string $handle, string $key, mixed $value );

引数の説明:

  • $handle (string) — 登録されたスタイルシートのハンドル。
  • $key (string) — 設定するデータの種類(例: ‘conditional’)。
  • $value (mixed) — 設定する値。

例1: 条件付きスタイルの追加

このコードは、特定の条件でスタイルシートを読み込む方法を示します。

wp_enqueue_style( 'example-style', get_template_directory_uri() . '/style.css' );
wp_style_add_data( 'example-style', 'conditional', 'lt IE 9' );

例2: RTLスタイルの設定

RTL(右から左への読み書き)向けのスタイルを設定します。

wp_enqueue_style( 'example-style', get_template_directory_uri() . '/style.css' );
wp_style_add_data( 'example-style', 'rtl', true );

例3: 異なるメディアの指定

このコードは、特定のメディアに適用されるスタイルを登録します。

wp_enqueue_style( 'example-style', get_template_directory_uri() . '/print.css', [], null, 'print' );
wp_style_add_data( 'example-style', 'media', 'screen and (max-width: 600px)' );

例4: カスタムデータの追加

カスタムデータをスタイルに追加します。

wp_enqueue_style( 'example-style', get_template_directory_uri() . '/style.css' );
wp_style_add_data( 'example-style', 'custom', 'example-value' );

例5: 非同期スタイルの設定

このコードは、非同期でスタイルを読み込む方法を示します。

wp_enqueue_style( 'example-style', get_template_directory_uri() . '/style.css' );
wp_style_add_data( 'example-style', 'preload', 'async' );

注意点

  • $handleが未登録の場合、エラーが発生します。
  • 不正な$keyを指定すると、期待した動作をしない場合があります。
  • この関数を使う際は、登録済みのスタイルハンドルを確認してください。

関連機能: