タイトル長いな。
今やってる案件で「この部分に毎月発行している広報誌をpdfで挿入できな?」てなご要望がありまして。
まずはやりたいこと

要するにthe_contentの間になにか挿入したわけです。
いつもなら「じゃあPDFの挿入の仕方教えますね」ぐらいなんですが、「できるだけ簡単に更新できるようにしてあげよう(予算いっぱいだし)」とか「毎月のことだしレイアウト崩されてもな(予算いっぱいだし)」とか思ってしまいまして、これは一肌脱ぐかって事になった次第です。
あ、でやりたいことは「the_contentを真っ二つに割って、そこにカスタムフィールドで作ったPDF挿入を表示する」です。
the_contentを真っ二つにする
じゃあどうしたらthe_contentを真っ二つにできるのか。
moreタグを使うとできます。
<?php if(strpos(get_the_content(),'id="more-')) :
global $more; $more = 0;
the_content('');
?>
// ここにPDFのリンクを作成
<?php
$more = 1;
the_content('', true );
else : the_content();
endif;
?>これは下記のサイトを参考にさせていただきました。
もうこれだけでやりたいことの9割は完成しましたね。
後はカスタムフィールドでPDFアップロードと○月号などのテキスト入力を作ってしまえば完成です。
一応、ボクが書いたテンプレートの一部とCustom Field Templateの設定を残しておきます。
Custom Field Template
[field0] type = fieldset_open legend = PDF multipul = true multipleButton = true [PDF] type = file [名称] type = text size = 50 [field0] type = fieldset_close
テンプレート
<?php if(have_posts()): while(have_posts()): the_post(); ?>
<h1><?php the_title(); ?></h1>
<div class="exp">
<?php if(strpos(get_the_content(),'id="more-')) :
global $more; $more = 0;
the_content(''); ?>
<div class="pdf">
<ul>
<?php
global $wpdb;
$query = "SELECT meta_id,post_id,meta_key,meta_value FROM $wpdb->postmeta WHERE post_id = $post->ID ORDER BY meta_id ASC";
$cf = $wpdb->get_results($query, ARRAY_A);
$pdf = array();
$meishou = array();
foreach($cf as $row) {
if($row['meta_key'] == "PDF"){
array_push($pdf, $row['meta_value']);
}
if($row['meta_key'] == "名称"){
array_push($meishou, $row['meta_value']);
}
}
$length = count($pdf);
for($i = 0; $i < $length; $i ++){
$file = wp_get_attachment_url($pdf[$i]);
?>
<li><a href="<?php echo $file; ?>" target="_blank"><?php echo $meishou[$i]; ?></a></li>
<?php } ?>
</ul>
</div>
<?php $more = 1;
the_content('', true );
else : the_content();
endif; ?>
</div>
<?php endwhile; endif; ?>まとめ
これが出来れば間にgoogle広告の挿入や、今回のようにカスタムフィールドの挿入も簡単にできます。
そもそもthe_contentを分割できるなんて知らなかったから目からウロコでした。


