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

2022-01-19 00:00:00 frontend javascript wordpress tinymce

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

I am trying to find out how to combine this code in resource box on a front end submission form but I need it to be limited to a certain number of characters.

<?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']; } } ?>

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

This code checks if the field is empty:

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

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

How can I make that check inside wp_editor function? I need this to allow and simplify html inside my resource box to users...

这是我在里面使用的 javascript 函数 ('onkeyup'=>'countChar(this)') 但它不起作用.

This is the javascript function that I am using ('onkeyup'=>'countChar(this)') inside but it's not working.

我在这儿摔倒了吗?

推荐答案

我根据自己的需要稍微修改了 Bryan Gentry 的解决方案,它运行良好.如果您需要类似的功能,这是我的代码.

I altered Bryan Gentry's solution a tiny bit to my needs and it works nicely. Here is my code if you need a similar functionality.

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;
}

相关文章