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

概要

get_parent_theme_file_uri 関数は、子テーマから親テーマ内にあるファイルのURIを取得するために使用されます。この関数は、特にテーマ開発やカスタマイズの際に役立ち、以下のような機能を実装する際によく使われます。

  1. 親テーマのスタイルシートを読み込む
  2. 親テーマのスクリプトを参照する
  3. 親テーマのテンプレート部分を参照する
  4. 親テーマの画像やメディアファイルを取得する
  5. CSSやJSのバージョン管理を行う
  6. カスタムロゴやアイコンを設定する
  7. 言語ファイルを参照する
  8. 親テーマのブロックエディタ用スタイルを追加する

構文

get_parent_theme_file_uri( $path );

パラメータ

  • $path (string) : 親テーマ内のファイルへの相対パス。省略可能。

戻り値

  • 親テーマ内の指定したファイルのURI。ファイルが存在しない場合は空の文字列を返します。

関連する関数

使用可能なバージョン

get_parent_theme_file_uri 関数は WordPress 4.7.0 以降で使用可能です。

コアファイルのパス

wp-includes/theme.php

サンプルコード

サンプル1: 親テーマのスタイルシートを読み込む

function my_theme_enqueue_styles() {
    wp_enqueue_style( 'parent-style', get_parent_theme_file_uri( 'style.css' ) );
}
add_action( 'wp_enqueue_scripts', 'my_theme_enqueue_styles' );

このコードは、親テーマのスタイルシートを子テーマで読み込むためのサンプルです。

サンプル2: 親テーマのスクリプトを読み込む

function my_theme_enqueue_scripts() {
    wp_enqueue_script( 'parent-script', get_parent_theme_file_uri( 'js/script.js' ) );
}
add_action( 'wp_enqueue_scripts', 'my_theme_enqueue_scripts' );

こちらは親テーマにあるJavaScriptファイルを子テーマで読み込む例です。

サンプル3: 親テーマの画像を取得する

function get_parent_image_url() {
    $image_url = get_parent_theme_file_uri( 'images/logo.png' );
    return $image_url;
}

このコードは、親テーマ内の画像のURLを返す関数です。

サンプル4: 親テーマのテンプレートを使用する

get_template_part( get_parent_theme_file_uri( 'template-parts/content', 'page' ) );

親テーマのテンプレートパーツを子テーマで取得する例です。

サンプル5: 親テーマのCSSをカスタマイズ

function my_custom_styles() {
    echo '<link rel="stylesheet" href="' . get_parent_theme_file_uri( 'css/custom.css' ) . '">';
}
add_action( 'wp_head', 'my_custom_styles' );

このコードは、親テーマにあるカスタムCSSファイルをページのヘッダーに追加する例です。

この関数のアクションでの使用可能性

アクション 使用例
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

非推奨のバージョン

現在のところ、get_parent_theme_file_uri 関数は特定のバージョンで非推奨又は削除されていません。

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


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