雖說 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 樣式,當然也可以自己動手。
這樣操作完成後,就可以最大程度上地強化 「所見即所得」 效果了。