<?php the_excerpt(); ?>
下記はfunctionに記載する。
「続きを読む」のパーマリンクを設定する
function tuzuki_excerpt_more( $post ) {
return '...'
. '<br>'
. '<i class="fa fa-caret-right" aria-hidden="true"></i>'
. '<a href="' . get_permalink( $post->ID ) . '">'
. '続きを読む'
. '</a>';
}
add_filter( 'excerpt_more', 'tuzuki_excerpt_more' );
<?php the_excerpt(); ?>で文字数を決める
function kazu_excerpt_length( $length ) {
return 100;
}
add_filter( 'excerpt_length', 'kazu_excerpt_length' );
文字数制限をしたい本文のテンプレートタグの代わりに下記のコードを記述。
<?php
if(mb_strlen($post->post_content, 'UTF-8')>120){
$content= mb_substr(strip_tags($post->post_content), 0, 120, 'UTF-8');
echo $content.'……';
} else {
echo strip_tags(->post_content);
}
?>
本文がHTMLタグも含め120文字より多い場合は、HTMLタグを削除した120文字を表示し、最後に「……」を付ける。
本文がHTMLタグも含め120文字以下の場合は、HTMLタグを外して全文表示。
文字数制限をしたい本文のテンプレートタグの代わりに下記のコードを記述。
<?php
if(mb_strlen($post->post_content, 'UTF-8')>120){
$content= mb_substr(strip_tags(apply_filters('the_content', $post->post_content), '<br><p><span>'), 0,120, 'UTF-8');
echo $content.'……';
} else {
echo strip_tags(apply_filters('the_content', $post->post_content),'<br><p><span>');
}
?>
本文がHTMLタグも含め120文字より多い場合は、
タグとタグとタグを残しそれ以外のHTMLタグを削除した120文字を表示し、最後に「……」を付ける。
本文がHTMLタグも含め120文字以下の場合は、
タグとタグとタグを残しそれ以外のHTMLタグを削除し全文を表示。
※補足:上記の「コードの例。」の3行目と6行目、
「strip_tags」の第1引数で渡す文字列を「$post->post_content」にしてしまうと、HTMLタグが全部無くなってしまう(というか、「$post->post_content」はWordpressが自動で加工・変換する前の生のデータ)ので、「$post->post_content」の代わりに「apply_filters(‘the_content’, $post->post_content)」を記述。
引用元:https://www.oikawa-sekkei.com/web/design/wordpress/wp-strip_tags.html