有没有办法在wp_editor函数中应用字符限制?

时间:2012-09-21 13:00:17

标签: javascript wordpress tinymce frontend

我正在尝试找出如何在前端提交表单的资源框中组合此代码,但我需要将其限制为一定数量的字符。

<?php wp_editor( get_option('resource'), 'resource', array('textarea_name' => 'resource', 'class'=>'requiredField', 'textarea_rows'=>'6','id'=>'resource' ,'onkeyup'=>'countChar(this)','media_buttons' => false)  );?><?php if(isset($_POST['resource'])) { if(function_exists('stripslashes')) { echo stripslashes($_POST['resource']); } else { echo $_POST['resource']; } } ?>

此代码检查字段是否为空:

<?php if(isset($_POST['resource'])) { if(function_exists('stripslashes')) { echo stripslashes($_POST['resource']); } else { echo $_POST['resource']; } } ?>

如何在wp_editor函数中进行检查?我需要这个来允许并简化我的资源框中的html给用户......

这是我正在使用的javascript函数('onkeyup'=&gt;'countChar(this)'),但它不起作用。

我来了吗?

2 个答案:

答案 0 :(得分:1)

首先,您需要更正wp_editor的实现。您的代码应该是这样的:

<?php wp_editor( get_option('resource'), 'resource', array('textarea_name' => 'resource', 'editor_class'=>'requiredField', 'textarea_rows'=>'6', 'media_buttons' => false)  );?>

请注意,the wp_editor function不接受javascript方法的参数,并且“editor_class”有一个参数,而不是“class”。

接下来,您需要将keyup事件(或keydown事件)绑定到TinyMCE编辑器。这需要在编辑器初始化时完成。 This other Q&A帮助我为您找到解决方案。您需要在functions.php文件中添加与以下内容类似的内容:

add_filter( 'tiny_mce_before_init', 'wpse24113_tiny_mce_before_init' );
function wpse24113_tiny_mce_before_init( $initArray )
    {
        $initArray['setup'] = <<<JS
                [function(ed) {
                ed.onKeyDown.add(function(ed, e) {
                   if(tinyMCE.activeEditor.editorId=='resource') || (tinyMCE.activeEditor.editorId=='the_other_editor_id_you_want_to_limit') {
                        countChar(tinyMCE.activeEditor.getContent());
                     }
                });
            }][0]
            JS;
    return $initArray;
    }

这将更改TinyMCE初始化以为您添加事件。触发事件(按下某个键)时,该函数将检查活动编辑器的ID,以查看它是否是您希望限制其字符数的编辑器之一。然后它抓取编辑器的内容并将其传递给countChar函数。

答案 1 :(得分:0)

我根据自己的需要改变了Bryan Gentry的解决方案并且效果很好。如果您需要类似的功能,这是我的代码。

add_filter( 'tiny_mce_before_init', 'wpse24113_tiny_mce_before_init' );
function wpse24113_tiny_mce_before_init( $initArray )
{
    $initArray['setup'] = <<<JS
[function(ed) {
    ed.onKeyDown.add(function(ed, e) {
        if(tinyMCE.activeEditor.editorId=='content-id') {
            var content = tinyMCE.activeEditor.getContent();
            var max = 300;
            var len = content.length;
            if (len >= max) {
              $('#charNum').html('<span class="text-error">You've got more then '+max+' characters!</span>');
            } else {
             var charCount = max - len;
             $('#charNum').html(charCount + ' characters left');
            }
         }
    });

}][0]
JS;
    return $initArray;
}