ファイルやディレクトリが存在するか調べるfile_existsをWordPressで使う場合の注意点

ファイルやディレクトリが存在するか調べるfile_existsをWordPressで使う場合の注意点

ファイルやディレクトリが存在するか調べるfile_existsをWordPressで使う場合の注意点

file_existsは、ファイルまたはディレクトリが存在するかどうか調べることができるPHPの関数です。

例えば、foo.txtというファイルが存在するかどうかを調べるには、以下のように記述します。


<?php
$filename = '/path/to/foo.txt';
if (file_exists($filename)) {
  echo "$filename が存在します";
} else {
  echo "$filename は存在しません";
}
?>

このfile_existsをWordPressで使う場合に、パスの指定でミスしそうな点について書きたいと思います。

スポンサードリンク

file_existsをWordPressで使う場合の注意点

私自身も最初ハマってしまったのですが、file_existsで指定するパスを取得する際に、get_template_directory_uri()やget_stylesheet_directory_uri()を使うと正常にfile_existsでファイルの有無をチェックできません。

パスを取得する際は、get_template_directory()を使います。子テーマの場合は、get_stylesheet_directory()ですね。


$path = get_template_directory() . "/example/example.jpg";

//子テーマの場合
$path = get_stylesheet_directory() . "/example/example.jpg";

//相対パスで指定する場合
$path = dirname( __FILE__ ) . "/example/example.jpg";

上述したようにパスを取得すれば、file_existsで正常に処理できます。

get_template_directory_uri()やget_stylesheet_directory_uri()の場合は「http://example.com/wp-content/themes/mytheme」といったURLが返ってきますが、get_template_directory()やget_stylesheet_directory()の場合は「/home/example.com/public_html/wp-content/themes/mytheme」といったようにパスが返ってきます。

file_existsではパスを指定しなければいけないので、get_template_directory_uri()やget_stylesheet_directory_uri()ではダメということですね。

あとがき

テーマ内でファイルのパスを取得する場合、get_template_directory_uri()やget_stylesheet_directory_uri()を使うことが多いと思いますが、file_existsの場合はget_template_directory()やget_stylesheet_directory()を使わなければいけないと覚えておきましょう。

この記事が気に入ったら
いいね!してね♪

Twitter で
スポンサードリンク

関連記事

コメントを残す

メールアドレスが公開されることはありません。 が付いている欄は必須項目です