WordPressで画像(ファイル)の有無判定

少しはまったのでメモを残しておきます。

画像が有るときは、対象の画像を表示して
無い場合はデフォルトの画像を表示するやり方

ファイル名は、main-image-WPのスラッグ名.pngと言うルールで製作
デフォルト画像はmain-image.pngとする。

それでは早速コードを紹介します。


post->ID

post->ID)->post_name .".png";
$images= get_stylesheet_directory() . $file_name;

if (file_exists($images)) {
//ファイルがある場合 
$images= get_template_directory_uri() ."/images/main-image-". get_post($wp_query->post->ID)->post_name .".png";
					
} else {
//ファイルが無い場合は、代替え画像を出力
$images= get_template_directory_uri() ."/images/main-image.png";
}
?>