投稿記事の抜粋the_excerpt()のカスタマイズ
一度設定してしまうと当たり前になってしまい設定していたことを忘れるのでメモ。WordPressでは記事の抜粋文を表示する場合、the_excerptというテンプレートタグを使う。抜粋文の最後に「続く」とかで本文にリンクさせるやつだ。
デフォルトの設定のままだと110文字で抜粋文の最後は[…]と残念な表記になる。
<?php the_excerpt(); ?>
抜粋する文字数を変更する場合はfunction.phpに以下を追加する。「return 80;」の数字は文字数。日本語でも半角英数でも記号でも同じ文字数になるようだ。
function custom_excerpt_length( $length ) {
return 80;//文字数を設定すべし
}
add_filter( 'excerpt_length', 'custom_excerpt_length', 999 );
[…]の表示を「…MORE」に変更した場合。さらに記事へのリンクも付ける。
function custom_excerpt_more($post) {
return '<a class="type-x" href="'. get_permalink($post->ID) . '">' . ' ...MORE' . '</a>';
}
add_filter('excerpt_more', 'custom_excerpt_more');
上記はすべての抜粋が同じ文字数になる。それでも問題はないがページにより文字数を変えたい場合の設定。まずはfunction.phpで大元の文字数を設定しておく。
function custom_excerpt_length($length){
return 200;//最大の抜粋文字数
}
add_filter('excerpt_length','custom_excerpt_length',999);
表示させるページthe_excerpt()を文字数を設定して以下に置き換える。上記の最大文字数以下で。
<?php echo mb_substr(get_the_excerpt(), 0, 80); ?>
get_the_content()を使う方法もあるが、HTMLとかのタグもそのまま表示されてしまうので除外する設定にしないといけない。設定してもショートカットとか表示されたり設定が面倒だったのでthe_excerpt()にしている。
<?php get_the_content(); ?>
function custom_excerpt($excerpt_length){
$my_excerpt = get_the_content();
$my_excerpt = strip_tags($my_excerpt);//HTMLタグを削除
$my_excerpt = strip_shortcodes($my_excerpt);//ショートカットキーで使う文字を削除
$my_excerpt = mb_substr($my_excerpt, 0, $excerpt_length) . '...';
echo $my_excerpt;
}
NOTICES
- 記事内容は実装させたものがほとんどですが自己責任で参考にしてください。