4年前に作ったサイトで今までは記事投稿を僕がやっていたサイトがある。
Web担当のスタッフさんが増えたこともあり、その方が今後更新していくことになった。
内容は、お客様からの声をアンケートで回収し、その記事をアンケート用紙のキャプチャと共に記事を投稿するというもの。WYSIWYG上で画像を置いて、alignleftを設定すればスタイルは設定してあるのできちんと表示されるんだけど、簡単な方が記事投稿も頻繁にやってもらえそうなので、カスタムフィールドを使うことにした。カスタムフィールドはやっぱりACF(Advanced Custom Fields)。
カスタムフィールドで画像を用意するのはいいんだけど、ちょっと考えたのは、今までのレイアウトは変更せずにという点。テンプレートを修正すると今までのエントリーにも影響するし、かといってこの頃は投稿のカテゴリ分けで作っていたから、新たにカスタム投稿タイプってわけにもいかない…。
んで作ってみた。
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/****************************************************************************/ | |
/* ! 画像のみカスタムフィールド */ | |
/****************************************************************************/ | |
add_image_size( 'thumb_398_563', 398, 563, true ); | |
add_image_size( 'thumb_150', 150, 150, true ); | |
function add_questionnaire() { | |
global $post; | |
$voice_post_title = $post->post_title; | |
$questionnaire_image = get_field( 'questionnaire_image', $post->ID ); | |
$size_398 = 'thumb_398_563'; | |
$size_150 = 'thumb_150'; | |
$img_small = wp_get_attachment_image_src( $questionnaire_image, $size_150 ); | |
$img_small_src = $img_small[0]; | |
$img_small_width = $img_small[1]; | |
$img_small_height = [2]; | |
$img_large = wp_get_attachment_image_src( $questionnaire_image, $size_398 ); | |
$img_large_src = $img_large[0]; | |
$img_large_width = $img_large[1]; | |
$img_large_height = $img_large[2]; | |
$img_alt = get_post_meta( $questionnaire_image, '_wp_attachment_image_alt', true ); | |
$img_caption = | |
$img_small_obj = '<img src="' . $img_small_src . '" width="' . $img_small_width . '" height="' . $img_small_height . '" alt="' . $img_alt . '" title="' . $img_alt . '" />'; | |
$img_large_obj = '<img src="' . $img_large_src . '" width="' . $img_large_width . '" height="' . $img_large_height . '" alt="' . $img_alt . '" title="' . $img_alt . '" />'; | |
$img_html = '<div id="attachment_' . $questionnaire_image . '" class="wp-caption alignright"><a href="' . $img_large_src . '" class="fancybox">' . $img_small_obj . '</a><p class="wp_caption-text" style="width: ' . $img_small_width . 'px;">患者さまの声「' . $voice_post_title . '」アンケート用紙</p></div>'; | |
if( $questionnaire_image ) { | |
$content = $img_html . $post->post_content; | |
} else { | |
$content = $post->post_content; | |
} | |
$content = apply_filters( 'the_content', $content ); | |
echo $content; | |
} | |
// テンプレートに | |
add_questionnaire(); |