「Recent Posts Widget Extendedプラグイン」を使用していて「抜粋」を表示するとき、HTMLタグを有効にするためのTipsです。
「Recent Posts Widget Extendedプラグイン」を使用していて「抜粋」も表示をする場合、通常は本文内のテキストをフィルターを通して先頭から何文字かを表示されるようになります。
ここで「本文内の先頭から何文字か表示」ではなく別の文章を表示したい場合に「抜粋」欄に入力すると 抜粋欄のテキストが表示されるようになります。
しかし、HTMLタグを除去するフィルターが通ってますので 抜粋欄にHTMLタグを入れても効きません。
そこで抜粋欄に入力したテキストをそのまま表示されるようにする小ワザを紹介します。
【注意】入力したものがそのまま出力されますので「抜粋」の編集時でHTMLタグを入力する場合は十分に注意してください。
コード
以下のコードを my-plugin.php またはテーマの functions.php に張り付けてください。
/** * Filters the text content after words have been trimmed. * @since 3.3.0 * @param string $text The trimmed text. * @param int $num_words The number of words to trim the text to. Default 55. * @param string $more An optional string to append to the end of the trimmed text, e.g. …. * @param string $original_text The text before it was trimmed. */ function nendebcom_wp_trim_words( $text, $num_words, $more, $original_text ) { global $post; $post_excerpt = isset( $post->post_excerpt ) ? $post->post_excerpt : ''; if ( $post_excerpt && $num_words == 50 ){ $text = wp_kses_post( $post_excerpt ); } return $text; } add_filter( 'wp_trim_words', 'nendebcom_wp_trim_words', 99, 4 );
【解説】
抜粋欄(excerpt)にデータがあって かつ「$num_words」がマッチした場合だけフィルター(wp_trim_words)を通さずに返します。
抜粋欄(excerpt)表示の場合は文字数制限はなくなります。
抜粋欄(excerpt)が空の場合は「Recent Posts Widget Extendedプラグイン」の仕様通りに表示(contentの一部表示)されます。
※他の部分でもここを通りますので 「Recent Posts Widget Extendedプラグイン」利用する時だけにするために $num_words で判断しています。
「$num_words == 50」の「50」の部分は ウィジェット設定での「Excerpt Length」の自分で設定した値と同じのにしてください。※サンプルのように特に「50」にしなくていいです。(但しWordPressデフォルトの「55」や「110」は使わないでください。)
【テスト環境】
「WordPress」ver 5.3.2
「Recent Posts Widget Extendedプラグイン」ver 0.9.9.7
参考
Recent Posts Widget Extended
https://ja.wordpress.org/plugins/recent-posts-widget-extended/
関数リファレンス/wp trim words
https://wpdocs.osdn.jp/%E9%96%A2%E6%95%B0%E3%83%AA%E3%83%95%E3%82%A1%E3%83%AC%E3%83%B3%E3%82%B9/wp_trim_words
関数リファレンス/wp kses post
https://wpdocs.osdn.jp/%E9%96%A2%E6%95%B0%E3%83%AA%E3%83%95%E3%82%A1%E3%83%AC%E3%83%B3%E3%82%B9/wp_kses_post