雖説 WordPress 內置的 TinyMCE 編輯器就是一款所見即所得 (WYSIWYG) 編輯器,然而我們在後台編輯好的文章和在前台看到的效果,總不十分一致。要讓後台編輯結果和前台顯示效果實現更高的匹配度,其實也不難。
簡單的説,只需要聲明新建一個專供供可視化編輯器使用的新 CSS 文件,如果該 CSS 文件中的樣式與當前主題中 CSS 文件樣式一致,那麼我們在編輯器中 「見到」 的文章,就是在前台 「得到」 的效果了。

(修改後的效果)
1. 聲明可視化編輯器的 CSS 文件
在 functions.php 里加上一行代碼來聲明可視化編輯器的 CSS:
| // Add CSS to Visual Editor add_editor_style('css/custom-editor-style.css'); |
作為參數的文件路徑是主題目錄的相對路徑。請確保在主題文件夾下的指定位置新建這個新的 CSS 文件。
2. 確保新 CSS 與原有 CSS 文件的共有類
新的 CSS 文件主要負責保存文章樣式。文章的 HTML 標記通常被圍在一個 container 元素中,類似於:
| <div > <!-- all content for entire post in here --> </div> |
新的 CSS 文件樣式有可能使用上面的類名稱來設定文章專用的樣式:
| .post h1, .post h2, .post h3, .post h4 { font-family: MuseoLight, Georgia, serif; font-weight: normal; margin: 0 0 10px 0; } .post h2 { font-size: 28px; } .post h2 { padding: 10px 180px 10px 15px; background: #237abf url(../images/title-bg.png) repeat-x; margin: 0; line-height: 1.3; font-size: 22px; } .post h2, .post h2 a { color: white; text-shadow: 0 1px 2px #143855; } .post h2 a:hover { color: #b8e0ff; } .post h3 { font-size: 20px; padding: 5px 0; margin: 30px 0 15px 0; border-top: 1px solid #ccc; border-bottom: 1px solid #ccc; } .post h4 { font-size: 18px; } .post p { margin: 0 0 10px 0; } .post pre { background: #eee; padding: 15px; overflow: auto; margin: 0 0 15px 0; border: 1px solid #ddd; } .post pre code { font-size: 11px; } .post code { background: #eee; font: 12px Monaco, Courier, Monospace; color: #0E304A; } .post h3 code { font-size: 18px; } .post acronym, abbr { border-bottom: 1px dotted #514031; cursor: help; } .post ins { text-decoration: underline; } .post del { text-decoration: line-through; } .post a { outline: none; text-decoration: none; color: #19517C; background: #eee; border: 1px solid #ddd; padding: 1px 3px 2px 3px; -webkit-border-radius: 3px; -khtml-border-radius: 3px; -moz-border-radius: 3px; border-radius: 3px; } .post a:hover { color: #fff; background: #143855; border: 1px solid #143855; } |
(代碼中的字體、字號等各項數值僅供參考)
由於可視化編輯器中沒有相同的類名稱,因此我們不能只是把上面的代碼複製並粘貼到新 CSS 樣式文件中,那樣並不能奏效。因此我們還需要強制可視化編輯器具有同一個類名。
將下面的代碼放入 functions.php 文件:
| // Add body class to Visual Editor to match class used live function mytheme_mce_settings( $initArray ){ $initArray['body_class'] = 'post'; return $initArray; } add_filter( 'tiny_mce_before_init', 'mytheme_mce_settings' ); |
這可能不及引用單個文件來的有效,但至少方便很多。如果你喜歡給不同文件分別設置 css 樣式,當然也可以自己動手。
這樣操作完成後,就可以最大程度上地強化 「所見即所得」 效果了。