WordPressでは記事文章の表示方法を自由にカスタマイズ出来ますが、なかでもトップページに記事の抜粋を並べたり、長い文章を適当な文字数でカットして「続きを読む」を表示させたいとこなど結構あるのではないでしょうか?

最も簡単な方法は、Moreタグ(<!–more–>)を投稿記事の任意の場所に挿入するやり方ですが、毎回記事投稿するたびにMoreタグを挿入するは案外面倒だったりするのではないかと思います。
そこで、Moreタグを挿入しなくても指定した文字数をオーバーした場合には「続きを読む」リンクが自動で挿入される簡単な方法をご紹介したいと思います。
前提条件として、WordPressをインストールすると標準で入っている『WP Multibyte Patch』というプラグインを有効化しておく必要があります。

WordPressをマルチバイト環境(日本語)でお使いの方ならば大抵このプラグインを有効化していると思いますが、WordPressに正しく日本語の文字数をカウントしてもらうためには、このプラグインを有効化しておくことが必要になります。
STEP1 テーマファイルを修正する
まずは、テーマディレクトリ内(「wp-content」の中の「themes」の中の自分が有効化しているテーマ内)の「content.php」の54行目付近の
1 |
the_content |
この部分を、
1 |
the_excerpt(); |
に書き換えて上書き保存をします。
以下のソースコードはテーマ「TwentyFourteen」のcontent.phpの54行目付近の書き換え前と書き換え後の内容になります。
▼書き換え前
52 53 54 55 56 57 58 59 60 61 62 |
<div> <?php /* この箇所 */the_content( __( 'Continue reading <span>→</span>', 'twentyfourteen' ) ); wp_link_pages( array( 'before' => '<div><span>' . __( 'Pages:', 'twentyfourteen' ) . '</span>', 'after' => '</div>', 'link_before' => '<span>', 'link_after' => '</span>', ) ); ?> </div><!-- .entry-content --> |
▼書き換え後
52 53 54 55 56 57 58 59 60 61 62 |
<div> <?php /* この箇所 */the_excerpt(); wp_link_pages( array( 'before' => '<div><span>' . __( 'Pages:', 'twentyfourteen' ) . '</span>', 'after' => '</div>', 'link_before' => '<span>', 'link_after' => '</span>', ) ); ?> </div><!-- .entry-content --> |
STEP2 function.phpにコードを追加する
テーマディレクトリ内(「wp-content」の中の「themes」の中の自分が有効化しているテーマ内)の「functions.php」に以下のコードを追加してみましょう。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
// 「続きを読む」をカスタマイズするためのコード function my_excerpt_more($post) { return '... <a href="'. get_permalink($post->ID) . '">' . ' 続きを読む' . '</a>'; } <p>// 抜粋(the_excerpt())を適当な文字数でカットして表示するコード</p> function my_trim_all_excerpt( $text = '' , $cut = 80 ) { $raw_excerpt = $text; if ( '' == $text ) { $text = get_the_content(''); $text = strip_shortcodes( $text ); $text = apply_filters('the_content', $text); $text = str_replace(']]>', ']]>', $text); $text = strip_tags($text); } $excerpt_mblength = apply_filters('excerpt_mblength', $cut ); $excerpt_more = my_excerpt_more( $post ); $text = wp_trim_words( $text, $excerpt_mblength, $excerpt_more ); return apply_filters('wp_trim_excerpt', $text, $raw_excerpt); } <p>// the_excerpt()にフィルターをかけるコード</p> remove_filter('get_the_excerpt', 'wp_trim_excerpt'); add_filter('get_the_excerpt', 'my_trim_all_excerpt' ); |
上記サンプルコードでは、「続きを読む」に詳細ページへのリンクがつくように設定していますが、単純に「…」としたい場合には、3行目のmy_excerpt_more関数を以下のように書き換えます。
1 2 3 |
function my_excerpt_more($post) { return '...'; } |
また、カットする文字数については、7行目の「$cut = 80」という箇所で設定されているので、130文字以上をカットしたい場合には「$cut = 130」と設定内容の変更をしてみてください。
1 |
function my_trim_all_excerpt( $text = '' , $cut = 130 ) { // ← $cutを130に変更 |
以上で、投稿時に自動的に記事を抜粋表示し、その後に「続きを読む」を表示する設定は完了です。
WordPress初心者の方でも10分~15分程度で設定できると思いますので、上記コードをそのままコピーしてお使いいただければと思います。