我們在使用 WordPress Shortcode API 開發插件的時候,有個比較麻煩的問題,就是 WordPress 會自動在 shortcode 內添加 br 或者 p 標簽,這樣可能會打亂你的原先預想的 HTML 結構和布局。
造成這個問題的原因是 WordPress 默認的日志內容處理流程中,wpautop(將回車轉換成 p 或者 br 標簽的函數)是在 Shortcode 前面運行的。所以我們的解決方案也是非常簡單,改變它們執行的順序,在當前主題的 functions.php 文件中添加:
remove_filter( 'the_content', 'wpautop' );
add_filter( 'the_content', 'wpautop' , 12);
這樣調整順序之后,你的 shortcode 里面的內容,就不會有自動添加的 p 或者 br 標簽,但是如果 shortcode 中部分的內容你又需要一些 p 或者 br 標簽用來換行的話,你需要自己手動在自己 shortcode 處理程序中添加 wpautop 來處理了。
function bio_shortcode($atts, $content = null) {
$content = wpautop(trim($content));
return '<div class="bio">' . $content . '</div>';
}
add_shortcode('bio', 'bio_shortcode');