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

ACF文章内容(wysiwyg_tinymce)字符限制验证:$value始终为空

解决ACF验证默认文章内容(TinyMCE编辑器)时$value为空的问题

你遇到的$value为空的问题,本质是ACF的acf/validate_value钩子只针对ACF自定义字段生效,而_post_content是WordPress原生的文章内容字段,不属于ACF字段范畴,所以无法通过这个钩子获取到提交的内容。

下面是针对WordPress原生文章内容的字符限制解决方案,使用WordPress原生钩子实现:

// 验证文章内容长度
add_filter('wp_insert_post_data', 'validate_post_content_length', 10, 2);
function validate_post_content_length($data, $postarr) {
    // 仅针对文章类型验证(可根据需要调整post_type)
    if ($postarr['post_type'] === 'post') {
        $raw_content = trim($data['post_content']);
        // 统计纯文本字符数(若需包含HTML标签,去掉strip_tags即可)
        $content_length = strlen(strip_tags($raw_content));
        
        if ($content_length === 0) {
            add_filter('redirect_post_location', fn($location) => add_query_arg('content_error', 'empty', $location));
        } elseif ($content_length > 200) {
            add_filter('redirect_post_location', fn($location) => add_query_arg('content_error', 'too_long', $location));
        }
    }
    return $data;
}

// 显示错误提示
add_action('admin_notices', 'show_post_content_validation_error');
function show_post_content_validation_error() {
    if (!isset($_GET['content_error'])) return;
    
    $error_msg = match($_GET['content_error']) {
        'empty' => __('文章内容不能为空。'),
        'too_long' => __('文章内容不能超过200个字符。'),
        default => ''
    };
    
    if ($error_msg) {
        echo '<div class="error"><p>' . esc_html($error_msg) . '</p></div>';
        // 清除错误参数,避免刷新重复提示
        remove_query_arg('content_error');
    }
}

代码说明:

  • wp_insert_post_data是WordPress保存文章时触发的钩子,能直接获取到待保存的文章内容$data['post_content']。
  • 用strip_tags过滤HTML标签后统计纯文本长度,若需要包含HTML标签的总字符数,直接使用strlen($raw_content)即可。
  • 通过redirect_post_location传递错误标识,再用admin_notices钩子在后台显示友好的错误提示。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.20 12:53:21