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

WordPress无需插件限制文章标题为60字符并实现超字数错误提示

WordPress无插件实现文章标题长度限制(最大60字符)方法

完全可以实现,只需要将两段代码添加到你当前使用主题的functions.php文件末尾即可,前端后台都会生效,同时会实时显示字符计数提示。

第一步:添加前端实时计数与限制逻辑

把以下代码添加到主题functions.php文件:

function limit_post_title_length() {
    global $post_type;
    // 仅针对文章(post)类型生效,如需支持页面可在数组中添加'page'
    if( in_array( $post_type, array( 'post' ) ) ) {
    ?>
    <script type="text/javascript">
    jQuery(document).ready(function($) {
        var maxTitleLength = 60;
        var titleInput = $('#titlewrap #title');
        
        // 追加计数显示元素
        titleInput.after('<div id="title-char-count" style="margin-top:5px;font-size:13px;"></div>');
        var countElement = $('#title-char-count');
        
        // 计数校验逻辑
        function checkTitleLength() {
            var currentLength = titleInput.val().length;
            countElement.text(currentLength + '/' + maxTitleLength);
            
            if(currentLength > maxTitleLength) {
                countElement.css('color', '#dc3232');
                countElement.text('您已超出最大允许字符数 ' + currentLength + '/' + maxTitleLength);
                // 禁用发布按钮避免误提交
                $('#publish').prop('disabled', true);
            } else {
                countElement.css('color', '#2e7d32');
                $('#publish').prop('disabled', false);
            }
        }
        
        // 页面加载时初始化校验
        checkTitleLength();
        // 标题内容变更时实时校验
        titleInput.on('input keyup paste', function() {
            checkTitleLength();
        });
    });
    </script>
    <?php
    }
}
add_action('admin_footer-post.php', 'limit_post_title_length');
add_action('admin_footer-post-new.php', 'limit_post_title_length');

第二步:添加后端提交校验(避免前端限制被绕过)

前端JS限制可以被用户通过浏览器调试工具绕过,因此需要追加后端校验逻辑,同样放到functions.php末尾:

function validate_post_title_length($post_id) {
    $post_type = get_post_type($post_id);
    // 仅校验文章类型,跳过自动保存、修订版本
    if ($post_type != 'post' || wp_is_post_autosave($post_id) || wp_is_post_revision($post_id)) {
        return;
    }
    $title_length = strlen(get_the_title($post_id));
    if ($title_length > 60) {
        // 终止提交返回错误提示
        wp_die('文章标题长度不能超过60字符,当前标题长度为' . $title_length . '字符,请返回修改后重新提交。');
    }
}
add_action('save_post', 'validate_post_title_length');

补充说明

  • 操作前请先备份主题的functions.php文件,避免代码输入错误导致网站异常
  • 代码默认只对文章(post)类型生效,如果需要限制页面、自定义文章类型的标题长度,自行修改代码里的$post_type判断逻辑即可
  • 如果需要调整最大字符限制,直接修改代码里的maxTitleLength和对应校验数值即可

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 08:06:04