file_exists関数の使い方

file_exists関数は第一引数にファイルまたはディレクトリのパスを文字列で指定します。指定したファイルまたはディレクトリが存在する場合はtrue、存在しない場合はfalseを返します。

file_exists('ファイルまたはディレクトリのパス');

WordPressのアクションフックwp_headで、headタグ内にローディング用のCSSをインラインで出力します。file_exists関数でCSSファイルの有無を確認し、存在する場合のみ処理を実行します。

//functions.php
function add_inline_style() {
  $buffer = '';
  if(file_exists('/common/css/style.css')) {
    $buffer = file_get_contents('/common/css/style.css');
  }
  echo '<style>'.$buffer.'</style>';
});
add_action( 'wp_head', 'add_inline_style' );

タイトルとURLをコピーしました