furoblog’s blog

妻と一緒にはじめました。1日1更新が目標です。

【#Wordpress】固定ページの中に新着記事一覧を表示する

f:id:furoblog:20190812155920p:plain

 

新規ビジネスシリーズでブログを立ち上げたのですが、トップページを固定ページにしました。

その関係で、新規記事一覧をページ内に組み込みたくなったので改修。

 

前提条件

 

です。基本バージョン無関係でいけると思ってますが一応^^

 

Wordpressにショートコードの作成

今回は汎用性を持たせるためにショートコードを作りました。

ショートコードとは記事の中に [sample] などのようにカッコで括った状態で文字列を追加してあげることで自分が改めて設定した内容を出力できます。

要するに定期文のようなものですね。

 

template-parts/newarticlelist.php
<?php
echo "test";
?>
functions.php
<?php
/*
* phpファイルを読み込むショートコード
*/
function include_newarticlelist_php( $atts ){
    ob_start();
    get_template_part('template-parts/newarticlelist'); // template-parts/newarticlelist.phpを読みこみ
    return ob_get_clean();
}
add_shortcode( 'include_newarticlelist', 'include_newarticlelist_php' );
?>

 

とし、記事の中で [newarticlelist] と記載すればtestと表示されるはずです!

Wordpressの固定ページに新着記事一覧を表示する

さて、ショートコードは出せましたか?

この調子で次は固定ページに新着記事を表示してあげましょう。

先ほどのfunction.phpを以下のように修正します。

 

<?php
// 記事の取得件数
$limit = 5;
// アイキャッチの画像サイズ
$imagesize = array(322.55, 322.55);
// アイキャッチが存在しない時のURL
$noimage_url = 'https://imageurl';
// 記事が存在しなかった時に表示する文言
$noarticle_message = '表示する記事はありませんでした。';
// 記事本文の表示文字数
$body_limit = 100;
// 記事取得に必要な引数
    $args = array(
'posts_per_page' => $limit,
'post_type' => array(
'post',
),
    );
    $the_query = new WP_Query( $args );
?>

<?php
if($the_query->have_posts()):
while($the_query->have_posts()) : $the_query->the_post();
$category = get_the_category();
$cat_name = $category[ 0 ]->cat_name;
$cat_slug = $category[ 0 ]->category_nicename;
?>

<div class="post_thumbnail">
<a href="<?php the_permalink(); ?>">
<?php
// アイキャッチ画像が設定されているかチェック
if(has_post_thumbnail()){
// アイキャッチ画像を表示する
the_post_thumbnail($imagesize);
}else{
// 代替画像を表示する
echo '<img src="' . $noimage_url . '" width="322.55" height="322.55" alt="No Image" />';
}
?>
</a>
</div>
<p class="titleWrap">
<span class="title"><b><?php echo get_the_title(); ?></b></span>
</p>
<!-- .titleWrap -->
<div class="text">
<p>
<?php
if ( mb_strlen( $post->post_content, 'UTF-8' ) > $body_limit ) {
$content = str_replace( '\n', '', mb_substr( strip_tags( $post->post_content ), 0, $body_limit, 'UTF-8' ) );
echo $content . '…';
} else {
echo str_replace( '\n', '', strip_tags( $post->post_content ) );
}
?>
</p>
<p><a href="<?php the_permalink(); ?>">Read more...</a></p><br>
</div>
<!-- .text -->
<?php
endwhile;
else :
echo '<p>' . $noarticle_message . '</p>';
endif;
wp_reset_postdata();
?>
<a class="btn" href="/blog/"><span>OTHER BLOG</span></a>

 

いかがでしたでしょうか?

出力部分の改修などはお好みでどうぞ!

 

furoblog.hatenablog.com