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

Hostinger上WordPress自定义文章类型加style属性报JSON错误

问题分析与解决方法

核心原因

这个403错误+JSON响应无效的问题,本质是自定义文章类型的内容过滤规则未允许style属性,或者Hostinger服务器端的安全规则拦截了包含style的请求。普通文章/页面默认开启了对style属性的支持,但自定义文章类型需要手动配置。

解决步骤

1. 排查Hostinger服务器安全拦截

Hostinger默认启用ModSecurity或防火墙规则,可能会将带有style属性的POST请求判定为恶意请求(如XSS防护):

  • 登录Hostinger后台,找到「Security」或「防火墙」选项,临时关闭ModSecurity测试是否解决问题。
  • 如果关闭后恢复正常,需要在防火墙规则里添加例外,允许wp-json/wp/v2/myupdates/*路径下的请求包含style属性。

2. 为自定义文章类型开启style属性支持

WordPress的kses过滤机制会限制HTML属性,自定义文章类型默认继承严格的过滤规则,需手动添加允许style属性的规则。在你的mu-plugins/post-types.php文件末尾添加以下代码:

// 允许自定义文章类型的HTML标签使用style属性
function allow_style_attributes_for_custom_post_types($allowedposttags, $context) {
    // 针对编辑后台上下文及目标自定义文章类型
    if ($context === 'post' && in_array(get_post_type(), ['myupdates', 'myfundraisers', 'mycampaigns'])) {
        // 为p标签添加style属性支持,可按需扩展其他标签
        if (isset($allowedposttags['p'])) {
            $allowedposttags['p']['style'] = [];
        }
        // 如需支持div、span等标签,同理添加
        // $allowedposttags['div']['style'] = [];
        // $allowedposttags['span']['style'] = [];
    }
    return $allowedposttags;
}
add_filter('wp_kses_allowed_html', 'allow_style_attributes_for_custom_post_types', 10, 2);

3. 调整REST API内容过滤规则

如果上述方法无效,可能是REST API的内容过滤单独限制了属性,添加以下代码强制允许自定义文章类型的REST请求包含style:

// 调整REST API的内容过滤规则
function custom_rest_api_kses_filter($prepared_post, $request) {
    $post_type = $prepared_post['post_type'];
    if (in_array($post_type, ['myupdates', 'myfundraisers', 'mycampaigns'])) {
        // 临时调整kses过滤规则,适配自定义文章类型
        remove_filter('content_save_pre', 'wp_filter_post_kses');
        add_filter('content_save_pre', 'wp_filter_kses');
    }
    return $prepared_post;
}
add_filter('rest_pre_insert_post', 'custom_rest_api_kses_filter', 10, 2);

测试验证

添加代码后刷新后台,重新编辑自定义文章类型的内容,添加带style属性的段落,检查是否能正常保存。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.13 21:33:13