WordPress のトップに最新の記事一覧を表示する(2)

前回は、WordPress に投稿した記事を最新から順に取得した。今回は、取得した記事を要約して表示する。

記事の要約を表示

WordPress には、記事の要約を表示するthe_excerpt()という関数が用意されている。しかし、文字数は110文字で固定(日本語版の場合、通常は55単語)されており、文字数を変更するためにフィルターを利用しなければならない。少し不便なので、PHP の関数を組み合わせて要約を作成することにした。
利用するのは、文字列から HTML/PHP のタグを削除するstrip_tags()と、(マルチバイト対応の)文字列の一部を得るmb_substr()の2つだ。実際のコードは、以下の通り。

<?php if ( have_posts() ) : ?> // 投稿がある場合
    <?php while ( have_posts() ) : the_post(); ?> // 投稿ごとにループ
    <article id="post-<?php the_ID(); ?>" <?php post_class(); ?>>
        // 投稿のヘッダー(タイトルなど)を表示
        <header class="entry-header">
            <?php the_post_thumbnail(); ?>
            <h1 class="entry-title"><a href="<?php the_permalink(); ?>" title="<?php echo esc_attr( sprintf( __( 'Permalink to %s', 'twentytwelve' ), the_title_attribute( 'echo=0' ) ) ); ?>" rel="bookmark"><?php the_title(); ?></a></h1>
        </header>
        // 投稿の本文を表示
        <div class="entry-content">
            <?php echo mb_substr(strip_tags(get_the_content()), 0, 200); ?> // 投稿のタグを削除してから先頭から200文字取得
            ...<a href="<?php the_permalink(); ?>" title="<?php echo esc_attr( sprintf( __( 'Permalink to %s', 'twentytwelve' ), the_title_attribute( 'echo=0' ) ) ); ?>" rel="bookmark">続きを読む</a><br/> // 投稿へのパーマリンクを表示
        </div>
        <div class="entry-meta-description"><?php twentytwelve_entry_meta(); ?></div> // 投稿のメタ情報を表示
    </article>
    <?php endwhile; ?>
<?php else : ?> // 投稿がない場合
...
<?php endif;

WordPress の投稿の文字列には HTML のタグが含まれているので最初に除去、次に先頭から200文字取得して表示している。

前後の投稿へのリンク

投稿を取得する際に query_posts() 関数を利用しているので、next_posts_link() や previous_posts_link() 関数を利用してリンクを表示できる(詳細は前回参照)。上記のコードの、<?php endwhile; ?> の後に、以下のコードを追加した。

<nav id="<?php echo esc_attr($html_id); ?>" class="navigation" role="navigation">
    <h3 class="assistive-text"><?php _e( 'Post navigation', 'twentytwelve' ); ?></h3>
    <span class="alignleft"><?php next_posts_link( __( '<span class="meta-nav">←</span> Older posts', 'twentytwelve' ) ); ?></span>
    <span class="alignright"><?php previous_posts_link( __( 'Newer posts <span class="meta-nav">→</span>', 'twentytwelve' ) ); ?></span>
</nav>

これで、ブログのトップに投稿した最新記事を8件ずつ表示できるようになり、ページの下部に「過去の投稿」と「新しい投稿」を設置できた。


コメントを残す

メールアドレスが公開されることはありません。 が付いている欄は必須項目です

Time limit is exhausted. Please reload CAPTCHA.