You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

调用WordPress TinyMCE遇getContent null错误,求解决方法

解决WordPress中TinyMCE通过Ajax获取内容时的"Cannot read property 'getContent' of null"错误

你遇到的这个错误核心原因很明确:tinymce.activeEditor返回了null——要么是当前没有激活的编辑器实例(比如用户没点击过编辑器就提交),要么是编辑器还没完成初始化,甚至是你找错了编辑器的引用方式。结合你的代码,我给你几个针对性的解决思路:

1. 放弃activeEditor,直接通过编辑器ID获取实例

你用wp_editor( '', 'tinymcecontenteditor' )创建了ID为tinymcecontenteditor的编辑器,这才是最可靠的引用依据,activeEditor只有在编辑器被点击激活后才会有值,完全不稳定。修改你的JS代码:

// 优先通过指定ID获取编辑器实例
var editor = tinymce.get('tinymcecontenteditor');
// 构建表单数据时先判断实例是否存在,避免报错
var form = { 
    action: "submit_user_data", 
    content: editor ? editor.getContent() : '', 
    title: $("#inputTitle").val(), 
    ingredients: $("#inputIngredients").val(), 
    time: $("#inputTime").val(), 
    utensils: $("#inputUtensils").val(), 
    level: $("#inputLevel").val(), 
    meal_type: $("#inputMealType").val() 
};

2. 确保编辑器完成初始化后再执行代码

如果你的Ajax提交逻辑是在页面刚加载就触发,或者编辑器还没加载完成就执行,也会导致tinymce.get()返回null。可以利用TinyMCE的初始化回调来包裹你的提交逻辑:

tinymce.init({
    selector: '#tinymcecontenteditor',
    // 编辑器初始化完成后才绑定事件
    init_instance_callback: function(editor) {
        $("#your-submit-button").on('click', function() {
            var content = editor.getContent();
            // 构建表单并发送Ajax请求
            var form = { 
                action: "submit_user_data", 
                content: content,
                // 其他字段...
            };
            // 这里记得用WordPress的全局ajaxurl变量作为请求地址
            $.ajax({
                url: ajaxurl,
                type: 'POST',
                data: form,
                success: function(res) {
                    // 处理成功响应
                }
            });
        });
    }
});

如果你是依赖WordPress自动初始化wp_editor,也可以监听全局的编辑器添加事件:

document.addEventListener('DOMContentLoaded', function() {
    tinymce.on('AddEditor', function(e) {
        if (e.editor.id === 'tinymcecontenteditor') {
            // 编辑器已加载完成,在这里绑定提交逻辑
        }
    });
});

3. 检查前端页面的TinyMCE脚本加载(如果是在前台使用编辑器)

如果你是在WordPress前台页面调用wp_editor,默认可能不会自动加载TinyMCE的相关脚本,需要在PHP中手动引入:

add_action('wp_enqueue_scripts', function() {
    wp_enqueue_script('tinymce');
    wp_enqueue_script('wp-editor');
});

另外要确认wp_editor的ID参数和你JS中使用的完全一致,大小写、拼写都不能错!

4. 加个回退方案,兼容编辑器加载失败的情况

wp_editor会自动生成一个隐藏的textarea,ID就是你指定的tinymcecontenteditor,所以可以做个兜底:如果TinyMCE实例不存在,直接取textarea的原生值:

var editor = tinymce.get('tinymcecontenteditor');
var content = editor ? editor.getContent() : $('#tinymcecontenteditor').val();

内容的提问来源于stack exchange,提问作者Jadeye

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 04:32:29