抜粋と「続きを読む」は似てるようだが、テンプレートタグが the_excerpt()
か the_content()
かで結果が異なるので注意。
抜粋 the_excerpt()
the_excerpt() で使われるテキストの優先順位と末尾の処理
- 投稿作成/編集画面 の抜粋文入力欄の内容
- ↑がなく、
<!-- more -->
タグがあればその前まで - ↑がなければ投稿本文の最初の55個の単語(日本語版の場合は110文字)が使われ、末尾に
[...]
がつく
全てにおいて抜粋のテキストからはHTMLタグと画像が除去される。
なお、the_excerpt()
そのままでは文末に本文へのリンクが作成されないので注意。
抜粋される文字数の変更
日本語の場合
必ず WP Multibyte Patchの機能を使うこと
http://eastcoder.com/code/wp-multibyte-patch/
/wp-content/plugins/wp-multibyte-patch/wpmp-config-sample-ja.php
を /wp-content/wpmp-config.php
にコピーして設定内容を変える
wpmp-config-sample-ja.php
<?php
$wpmp_conf['excerpt_mblength'] = 10;
日本語以外の場合
「単語数」なので注意
excerpt-length.php
<?php
/**
* Filter the except length to 20 characters.
*
* @param int $length Excerpt length.
* @return int (Maybe) modified excerpt length.
*/
function wpdocs_custom_excerpt_length( $length ) {
return 20;
}
add_filter( 'excerpt_length', 'wpdocs_custom_excerpt_length', 999 );
行末の処理を変える
自動抜粋の場合、[...]
ではなく...
に変更
wpdocs-excerpt-more.php
<?php
/**
* Filter the excerpt "read more" string.
*
* @param string $more "Read more" excerpt string.
* @return string (Maybe) modified "read more" excerpt string.
*/
function wpdocs_excerpt_more( $more ) {
return '...';
}
add_filter( 'excerpt_more', 'wpdocs_excerpt_more' );
必ず末尾にリンク
Code Reference で紹介されているコードは自動抜粋の場合の処理なので、必ずなら get_the_excerpt
フィルターで処理した方がいいかも
get-the-excerpt-add_link.php
<?php
/**
* Filter the excerpt string link to the post.
*
* @param string $post_excerpt The post excerpt.
* @param WP_Post $post Post object.
* @return string (Maybe) modified "read more" excerpt string.
*/
function my_get_the_excerpt( $post_excerpt, $post ) {
$more = sprintf( '<a class="more-link" href="%1$s">%2$s</a>',
get_permalink( $post->ID ),
__( 'Read More', 'textdomain' )
);
return $post_excerpt . $more;
}
add_filter( 'get_the_excerpt', 'my_get_the_excerpt', 10, 2 );
続きを読む the_content()
アーカイブ系では <!-- more -->
タグがあればその前まで表示するが、反面、毎回投稿作成時に手動でタグを入れなければならない。
デフォルトで入るアンカーをなくす
remove-more-link-scroll.php
<?php
function remove_more_link_scroll( $link ) {
$link = preg_replace( '|#more-[0-9]+|', '', $link );
return $link;
}
add_filter( 'the_content_more_link', 'remove_more_link_scroll' );