将文本区域替换为WordPress TinyMCE wp_editor()


Replacing a textarea with WordPress TinyMCE wp_editor()

我正在尝试用wp_editor((替换文本区域

我的文本区域表单元素如下所示:

<textarea name="post_text" id="post_text" rows="3"><?php echo $content; ?></textarea>

然后我有:

wp_editor( $content, 'post_text' );

我遇到的问题是表单文本区域和wp_editor文本区域都输出在页面上。为什么两个文本区域都显示?我只需要一个文本区域来显示。一切都保存得很好,我只是有显示 2 个文本区域的问题。

编辑:是否像在表单的文本区域上放置display: none;一样简单,以便仅显示wp_editor((文本区域?这似乎有效,但感觉有点黑客。

我找到了解决方案。可以使用第三个参数传递参数数组。现在,正如法典中所概述的那样,这一点非常明显:http://codex.wordpress.org/Function_Reference/wp_editor

有点令人困惑(我问题的根源(是$editor_id可能只包含小写字母。因此,如果您的表单处理脚本正在寻找带有下划线的内容(就像我的一样(,那么您需要这样做:

$settings = array( 'textarea_name' => 'post_text' )
wp_editor( $content, $editor_id, $settings );

请注意,您不能这样做:

wp_editor( $content, 'post_text' );

这就是我出错的地方。

如果在代码中放置文本区域

<textarea></textarea>

然后它当然会出现在页面上,这是它应该做的。 除非有什么我误解的地方,否则我不认为这有什么意义。

就像你建议的,我认为这将做你想要的:

<textarea style="display:none" name="post_text" id="posttext" rows="3"><?php echo $content; ?></textarea>

它在功能上仍然会在那里,但看不见。

下面的PHP代码变成了一个文本区域,名称和id为"expirationErrorMessage"。

$id = "expirationErrorMessage";
$name = 'expirationErrorMessage';
$content = esc_textarea( stripslashes( $yourtext ) );
$settings = array('tinymce' => true, 'textarea_name' => $name);
wp_editor($content, $id, $settings);

而不是将新的文本区域输出到页面(通过 wp_editor() (并用 display: none; 隐藏原始文本区域,可以这样做:

add_action('admin_init', '20331501_convert_textarea_to_wysiwyg');
function 20331501_convert_textarea_to_wysiwyg(){
    wp_enqueue_editor();
    add_action( 'admin_print_footer_scripts', function() {
        ?>
        <script>
            jQuery(function(){
                wp.editor.initialize('the-id-of-your-textarea-without-the-#', {
                    setup: function (editor) {
                        editor.on('change', function () {
                            editor.save();
                        });
                    }
                });
            });
        </script>
        <?php
    }, 10, 2 );
}

此代码片段将现有文本区域转换为所见即所得。editor.save()负责更新文本区域值,以便在提交表单时传递该值。(感谢@Dan马尔科姆(

在您希望放置tinyMCE的位置调用您的template pagetemplate page放置一个placeholder,例如CONTENT_EDITOR并使用 php str_replace 函数向该template内容添加tinyMCE

function add_tinymce_to_page(){
    $creatorHTML                    =   file_get_contents(
        'your-template-pafe.php',
        TRUE
    );
    $editorHTML                     = generate_content_with_editor();
    $creatorHTML                    =   str_replace(
        'CONTENT_EDITOR',
        $editorHTML,
        $creatorHTML
    );
    return $creatorHTML;
}
function generate_content_with_editor(){
    ob_start();
    wp_editor( '', 'tinymcecontenteditor' );
    $editor_contents                = ob_get_contents();
    ob_get_clean();
    return $editor_contents;
}

我使用 phpob,因此tinyMCE在呈现整页之前不会显示。