あくまで自分用の覚え書きなので文章とか適当です...

OGPのディスクリプションや投稿一覧に本文の抜粋を出力するときなどに無駄な Gutenberg ブロックタグやHTML要素を省いて文字数を制限して表示する方法

$cont = get_the_content();
$cont = wp_strip_all_tags( $cont, true );
$cont = trim( strip_shortcodes( $cont ) );
$cont = str_replace( array( "\r\n", "\r", "\n" ), '', $cont );
$cont = str_replace( ' ', '', $cont );
$cont = mb_strlen( $cont, 'UTF-8' ) > 31 ? mb_substr( $cont, 0, 31 ) . '…' : $cont;
$cont = trim( $cont ); // 最初と最後のスペースをtrim
echo esc_html( $cont );
スポンサーリンク