Customize Consent Preferences

We use cookies to help you navigate efficiently and perform certain functions. You will find detailed information about all cookies under each consent category below.

The cookies that are categorized as "Necessary" are stored on your browser as they are essential for enabling the basic functionalities of the site. ... 

Always Active

Necessary cookies are required to enable the basic features of this site, such as providing secure log-in or adjusting your consent preferences. These cookies do not store any personally identifiable data.

No cookies to display.

Functional cookies help perform certain functionalities like sharing the content of the website on social media platforms, collecting feedback, and other third-party features.

No cookies to display.

Analytical cookies are used to understand how visitors interact with the website. These cookies help provide information on metrics such as the number of visitors, bounce rate, traffic source, etc.

No cookies to display.

Performance cookies are used to understand and analyze the key performance indexes of the website which helps in delivering a better user experience for the visitors.

No cookies to display.

Advertisement cookies are used to provide visitors with customized advertisements based on the pages you visited previously and to analyze the effectiveness of the ad campaigns.

No cookies to display.

WordPress Snippet

ワードプレスをカスタマイズしよう

画像の存在を確認しないで、代替画像を表示する

アイキャッチ画像の表示などで、アイキャッチ画像が存在する場合にはその画像を表示し、存在しない場合には、代替画像を表示する

といった作業が必要になる事があります。

このような作業を行う場合、PHPやjavascript等を記述する必要があり、ハードルが高かったりします。

WordPressの日本語フォーラムで、以下のような質問がありました。

この場合、難しい条件分岐のコードを記述せずに、代替画像を表示出来るか 考えてみます。

この質問では、タイトルスラッグと同名の画像が、テーマのimages/title/の中に、存在するので、対応するURLを取得します。

固定ページで、表示画像の取得

$page_slug= get_query_var('pagename');
$image_url= get_template_directory_uri(). '/images/title/'. $page_slug . '.jpg';

しかし、このURLのjpgファイルは、存在するかどうかは、不確かです。

さてここからが、この記事のアイディアです。

img 要素は使用せず、div 要素とbackground プロパティを使う事にします。

スタイルシート

style.css にスタイルを記述します。

.page-image-container{
		width:600px;
		max-width:100%;
		height:400px;
		border:1px solid #000;
	}

div要素のサイズや、ボーダーを指定しました。

テンプレートにコードの追加

page.php

//まずは、先ほどの $image_url のコードを記述します。 

$page_slug= get_query_var('pagename');
$image_url= get_template_directory_uri(). '/images/title/'. $page_slug . '.jpg';

//次に 代替画像のURLを記述します
$fallback_url= "http://example.com/fallback-image.jpg";
//次に、画像表示用のdiv要素を記述します

<div class="page-image-container" style="background:url( <?php echo $image_url; ?> ),url(<?php echo $fallback_url; ?>);background-size:cover;"><div>

以上で、$image_urlが存在しない場合、$fallback_url が表示されるようになります。

関連リンク

マルチバッググラウンドと、background-size をうまく使うと、条件分岐ができてしまいます。

[emulsion_relate_posts]