記事の一覧表示をさせる時に文章(テキスト)だけを文字数制限して抜粋する場合、
タグやショートコードまでそのまま表示されてしまうのを防ぐ手段。
例:150文字の制限で改行・タグ・ショートコードを取り除くもの
<p><?php
if(mb_strlen($post->post_content,'UTF-8')>150){
$content= str_replace('\n', '', mb_substr(strip_tags(strip_shortcodes($post-> post_content)), 0, 150,'UTF-8'));
echo $content.'...';
}else{
echo str_replace('\n', '', strip_tags($post->post_content));
}
?>
</p>
str_replaceは改行コード、strip_tagsはタグ、strip_shortcodesはショートコード
参考資料
function.phpに記述
//使用方法:http://nelog.jp/get_the_custom_excerpt
function get_the_custom_excerpt($content, $length) {
$length = ($length ? $length : 70);//デフォルトの長さを指定する
$content = preg_replace('/<!--more-->.+/is',"",$content); //moreタグ以降削除
$content = strip_shortcodes($content);//ショートコード削除
$content = strip_tags($content);//タグの除去
$content = str_replace(" ","",$content);//特殊文字の削除(今回はスペースのみ)
$content = mb_substr($content,0,$length);//文字列を指定した長さで切り取る
return $content;
}
テンプレート内に記述
<?php echo get_the_custom_excerpt( get_the_content(), 150 ) ?>