ワードプレスの便利なプラグイン『Advanced Custom Fields』
カスタマイズする時にコレが有るとかなり色々出来る。
今回はチェックボックスを文字列ではなく、チェックした項目に用意した画像を表示するように指定したいと思い、悪戦苦闘したのでメモ書き
*今回の例は、共通の画像を使いたいが、ページによって1、2、3、4の画像を任意で消したり出したりしたい場合の処理です。
1にチェックが入っていたら1の画像を呼び出したい・・・のような場合。
*最初に()括弧の数字はどこで使っているかを示す為のものなので、実際には使いません
例 ”(0)test_img” = “test_img”です。
まずはカスタムフィールド
field_name・・・今回は”(0)test_img”とします
次にチェック項目(チェックボックスの値)
(1)img1:画像1
(2)img2:画像2
(3)img3:画像3
(4)img4:画像4
とします
挿入したい画像は自身のテーマ(test)の中に格納していると仮定
格納場所とは(今回の場合はtestフォルダ(テーマ名)の中のcommonフォルダの中のimgフォルダの中なので)
/themes/test/common/img/ココ
自身が使用しているテーマの直下のcommonの中のimgフォルダに格納
絶対パスは
http://test.com/wp-content/themes/test/common/img/img1.jpg
となります。
※人によってはこのパスが変わります。
例えば、テーマの直下にimgフォルダを置く人もいれば、index.phpと同じ階層に直接img画像を置く人もいる(オススメしないけど)
直下(index.phpと同じ階層)に置く人の場合の絶対パス
http://test.com/wp-content/themes/test/img1.jpg
記述はこのようになる
<?php if(get_field('$field_name
'))
{
if( in_array( ‘チェックボックスの値‘, get_field(‘$field_name
‘) ) ){
echo ‘<img src=”http://●●●.com/■■■/wp-content/themes/▲▲▲/common/img/×××.jpg” width=”100″ alt=”画像”>’;
}
}
?>
ここからは記述したいファイル(test.php)
挿入したい箇所に下記を記入
<dl>
<dt>画像入れたいよー</dt>
<dd>ここに表示したい</dd>
</dl>
こうする
<dl>
<dt>画像入れたいよー</dt>
<dd><!–この中に表示したい–>
<?php if(get_field(‘(0)test_img‘)) //$field_nameに自身のカスタムフィールドのフィールド名
{
if( in_array( ‘(1)img1‘, get_field(‘(0)test_img‘) ) ){
echo'<img src=”http://test.com/wp-content/themes/test/common/img/img1.jpg” width=”100″ alt=”画像1″>’;
}
}
?>
</dd>
</dl>
複数表示したい場合
<?php if(get_field('test_img')) //$field_nameに自身のカスタムフィールドのフィールド名
{
if( in_array( '(1)img1', get_field('(0)test_img') ) ){
echo'<img src="http://test.com/wp-content/themes/test/common/img/img1.jpg" width="100" alt="画像1">';
};if( in_array( '(2)img2', get_field('(0)test_img') ) ){
echo'<img src="http://test.com/wp-content/themes/test/common/img/img2.jpg" width="100" alt="画像2">';
};if( in_array( '(3)img3', get_field('(0)test_img') ) ){
echo'<img src="http://test.com/wp-content/themes/test/common/img/img3.jpg" width="100" alt="画像3">';
};if( in_array( '(4)img4', get_field('(0)test_img') ) ){
echo'<img src="http://test.com/wp-content/themes/test/common/img/img4.jpg" width="100" alt="画像4">';
};
}
?>
で表示出来た。
解説
if( in_array( '(1)img1', get_field('(0)test_img') ) ){
echo'<img src="http://test.com/wp-content/themes/test/common/img/img1.jpg" width="100" alt="画像1">';
};
get_fieldでフィールドステータスの読み込み
ステータスが(1)img1だった場合
echo'<img src=”http://test.com/wp-content/themes/test/common/img/img1.jpg” width=”100″ alt=”画像1″>’;
を引き出す
*このimg1.jpgは自信が使いたい画像なので、フィールドの値((1)img1)と名前を同じにする必要はない
また、カスタムフィールドに画像を入れていて、自動で出力したい場合はまた記述が変わりますので、今度書きたいと思う