WPのトップカスタマイズ-コンテンツの途中に新着記事をアイキャッチで入れる
トップページや普通の固定ページの内容途中に、アイキャッチ付きのカテゴリー新着記事を置きたい時ってありますよね。
やりたい事-コンテンツ内容の途中に新着記事(お客様の声)を見せる
完成イメージはこんな感じ。トップページや、それ用のページのPHPに一覧表示を直接書いてしまう方法もあるが、後々のメンテナンスを考えると若干面倒なので
新着記事を表示させるPHPをショートコードで呼び出し、コンテンツの途中に表示させる事にします。
アイキャッチ付き新着記事のテンプレートを用意する
<?php /* Template Name: お客様の声一覧 */ ?> <?php $cat = 'cs'; $num = '3'; global $post; $term_id = get_category_by_slug($cat)->term_id; $myposts = get_posts('numberposts=' .$num. '&category_name=' .$cat); if ($myposts) { echo '<div class="new-post-wrap">'; foreach($myposts as $post): setup_postdata($post); echo '<div class="post-list"><figure class="eyecatch"><a href=' .get_permalink(). '>'; if ( has_post_thumbnail() ) { echo ''.get_the_post_thumbnail($page->ID, 'thumbnail'.'300_thumbnail'). ''; } else { echo '<span class="no_image"><i class="fa fa-ban fa-2x" aria-hidden="true"></i> No images</span>'; } echo '</a></figure><div class="entry-meta">'; echo '<h4><a href='.get_permalink().'>'. the_title("","",false).'</h4>'; echo '<p>' .mb_substr( strip_tags( $post -> post_content ), 0, 150 ). '..続きを読む ≫</p></a></div></div>'; endforeach; echo '</div><center><a href=' .get_category_link($term_id). ' class="square_btn">お客様の声をもっと読む <i class="fa fa-chevron-right"></i></a></center>'; } else { echo '<p>記事がありません。</p>'; } ?>
今回はコンテンツ途中に「お客様の声」を3件横並びで入れる設定。
$cat = 'cs'; は表示するカテゴリーのスラッグです。
$num = '3'; は表示件数。
150 は続きを読む左にある150は表示文字数です。
上記のファイルをエディターで1枚作り「top_voise.php」と言う名前(仮)で保存し、テンプレートの他のPHPファイルと同じ階層にFTPで上げます。
ショートコードを使えるようにする
コンテンツ本文内にショートコードを使えるようにfunctions.phpに以下を追記します。
//ショートコードファイルの呼び出し方法 function my_php_Include($params = array()) { extract(shortcode_atts(array('file' => 'default'), $params)); ob_start(); include(STYLESHEETPATH . "/$file.php"); return ob_get_clean(); } add_shortcode('myphp', 'my_php_Include');
ここまで出来たらほぼ完成です。
コンテンツ本文にショートコードを加える
コンテンツ内容の途中に、先程の1枚作った「top_voise.php」を呼び出します。
こんな感じ。ファイル名を変更していた場合は名称を変更してね。
※ショートコードを加える時はかならずテキストエディターの方で加えましょう。
[myphp file='top_voise']
いかがでしょうか。3件表示されていたら成功です。
あとはCSSに追加し整えてあげましょう。
CSSで整える
/* お客様の声 */ .post-list { color:#333; text-decoration:none; display:block; overflow:hidden; border:3px solid #333; background:#fff; padding:.5em; margin-bottom:1em; } .post-list .eyecatch{ width:30%; float:left; margin:0 1em 0 0; padding:0; } .post-list .entry-title{ font-size:1.1em; font-weight:bold; } .post-list a{ text-decoration:none; }