ワードプレスのget_stylesheet_directory_uri関数の使用方法・解説

概要

get_stylesheet_directory_uri 関数は、現在の子テーマまたは親テーマのスタイルシートディレクトリの URL を取得するための WordPress の組み込み関数です。この関数は、テーマの CSS ファイルやスクリプト、画像などのリソースにアクセスする際によく使用されます。具体的には、次のような機能を実装する際によく使用されます:

  1. テーマのスタイルシートをエンキューするため
  2. テーマ内の画像を表示するため
  3. テーマのスクリプトファイルを読み込むため
  4. カスタムフォントを読み込むため
  5. テンプレートファイルからスタイルシートを参照するため
  6. ヘッダーやフッターにカスタム CSS を追加するため
  7. テンプレートのカスタマイズを行うため
  8. プラグインがテーマのスタイルを適切に読み込むため

構文

get_stylesheet_directory_uri();

パラメータ

この関数にはパラメータはありません。

戻り値

get_stylesheet_directory_uri 関数は、現在のテーマのスタイルシートディレクトリの URL を文字列として返します。

関連する関数

使用可能なバージョン

この関数は、WordPress 2.0.0 以降で使用可能です。

コアファイルのパス

get_stylesheet_directory_uri 関数は、wp-includes/theme.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. スタイルシートのエンキュー

このサンプルコードでは、テーマの style.css ファイルを正しくエンキューします。

function my_theme_enqueue_styles() {
    wp_enqueue_style('my-theme-style', get_stylesheet_directory_uri() . '/style.css');
}
add_action('wp_enqueue_scripts', 'my_theme_enqueue_styles');

引用元: https://developer.wordpress.org/reference/functions/get_stylesheet_directory_uri/

2. カスタム画像の表示

このサンプルコードは、テーマのディレクトリからカスタム画像を取得して表示します。

<img src="<?php echo get_stylesheet_directory_uri(); ?>/images/my-image.jpg" alt="My Image">

引用元: https://developer.wordpress.org/reference/functions/get_stylesheet_directory_uri/

3. スクリプトのエンキュー

テーマの JavaScript ファイルをエンキューするサンプルです。

function my_theme_enqueue_scripts() {
    wp_enqueue_script('my-theme-script', get_stylesheet_directory_uri() . '/js/my-script.js', array('jquery'), null, true);
}
add_action('wp_enqueue_scripts', 'my_theme_enqueue_scripts');

引用元: https://developer.wordpress.org/reference/functions/get_stylesheet_directory_uri/

4. 外部フォントの追加

このコードは、外部フォントをテーマに追加します。

function my_theme_add_google_fonts() {
    wp_enqueue_style('my-google-fonts', get_stylesheet_directory_uri() . '/fonts/my-font.woff2', false);
}
add_action('wp_enqueue_scripts', 'my_theme_add_google_fonts');

引用元: https://developer.wordpress.org/reference/functions/get_stylesheet_directory_uri/

5. テンプレートファイルからリソースを取得

テンプレートファイル内でリソースを取得するサンプルです。

<link rel="stylesheet" type="text/css" href="<?php echo get_stylesheet_directory_uri(); ?>/css/custom.css">

引用元: https://developer.wordpress.org/reference/functions/get_stylesheet_directory_uri/

この関数は、特定のバージョンで非推奨または削除された情報はありません。

この関数について質問する


上の計算式の答えを入力してください