Skip to content

Instantly share code, notes, and snippets.

@wokamoto
Last active August 29, 2015 14:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save wokamoto/11365599 to your computer and use it in GitHub Desktop.
Save wokamoto/11365599 to your computer and use it in GitHub Desktop.
にしかわさんへ
<?php
add_filter('the_content', 'my_shortcode', 7);
function my_shortcode( $content ) {
global $shortcode_tags;
$shortcode_tags_org = $shortcode_tags;
remove_all_shortcodes();
add_shortcode('code', 'my_shortcode_handler');
$content = do_shortcode( $content );
$shortcode_tags = $shortcode_tags_org;
return $content;
}
function my_shortcode_handler($atts, $content = null) {
extract(shortcode_atts(array(
'class' => 'code',
'encode' => 'true',
), $atts));
if (strtolower($encode) === 'true')
$content = htmlentities($content, ENT_QUOTES, get_option('blog_charset'));
return sprintf(
'<pre class="%s"><code>%s</code></pre>'."\n\n",
esc_attr($class),
esc_html($content),
);
}
<?php
add_shortcode('code', 'my_shortcode_handler');
function my_shortcode_handler($atts, $content = null) {
extract(shortcode_atts(array(
'class' => 'code',
'encode' => 'true',
), $atts));
if (strtolower($encode) === 'true')
$content = htmlentities($content, ENT_QUOTES, get_option('blog_charset'));
return sprintf(
'<pre class="%s"><code>%s</code></pre>'."\n\n",
esc_attr($class),
esc_html($content),
);
}
@wokamoto
Copy link
Author

[code] ショートコード内に書かれた文字列を htmlentities() して pre, code タグで囲む WordPress 用ショートコードのサンプルです。
strip_tags() しても内容が同じなら中に html タグが無いと判断して htmlentities() しません。

@wokamoto
Copy link
Author

gistfile2.php の方だと the_content フィルターフックに登録されている autop 通ると勝手に br とか p が [code] [/code] の中にも入っちゃって、思ったような出力にならないので、gistfile1.php では、いったんこのショートコードだけ実行させてます。
ちょいトリッキー

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment