技術ブログ
wordpressでhtmlタグをとる方法 – wp_strip_all_tags
htmlタグを削除
php一般にはstrip_tags関数を使用する。
wordpressでは独自のwp_strip_all_tags関数があるが、この関数でも内部でstrip_tagsが使用されている。
wp_strip_all_tagsではと
全体を除去する。これがstrip_tagsとの差異です。
ショートコードを削除する場合は、strip_shortcodes関数を使用する。
wp_strip_all_tags関数の定義は以下
/**
* Properly strip all HTML tags including script and style
*
* This differs from strip_tags() because it removes the contents of
* the `' )`
* will return 'something'. wp_strip_all_tags will return ''
*
* @since 2.9.0
*
* @param string $string String containing HTML tags
* @param bool $remove_breaks Optional. Whether to remove left over line breaks and white space chars
* @return string The processed string.
*/
function wp_strip_all_tags( $string, $remove_breaks = false ) {
$string = preg_replace( '@<(script|style)[^>]*?>.*?\\1>@si', '', $string );
$string = strip_tags( $string );
if ( $remove_breaks ) {
$string = preg_replace( '/[\r\n\t ]+/', ' ', $string );
}
return trim( $string );
}
$mycontents = get_the_content(); //HTMLタグ除去 $mycontents = wp_strip_all_tags( $mycontents ); //ショートコード除去 $mycontents = strip_shortcodes( $mycontents ); echo $mycontents;