dongshen2903 2017-04-18 08:40
浏览 17
已采纳

如何在wordpress帖子中设置最小字数

I am planning to create a code filter and set a minimum word count in saving/submitting the wordpress post. I tried this code.

function minWord($content)
{
    global $post;
    $content = $post->post_content;
    if (str_word_count($content) < 300 ) //set this to the minimum number of words
    wp_die( __('Error: your post is below the minimum word count. It needs to be longer than 300 words.') );
}
add_action('publish_post', 'minWord');

but the issue, when I input < 300 words the post still saves it on the database. My question now is what should I do that if the content will have < 300 words it won't save to the database?

  • 写回答

2条回答 默认 最新

  • dongxing5525 2017-04-18 14:02
    关注

    The wp_insert_post_data hook will be called before the post is saved to the database. We also check the status of the post so this function doesn't run on other admin pages.

    function enforceMinWordCount( $data, $post )
    {           
        if ($data['post_status'] === 'publish' &&
            str_word_count($post['post_content']) < 300 ) {
            wp_die( __('Error: your post is below the minimum word count. It needs to be longer than 300 words.') );
    
        }
        return $data;
    }
    
    add_action( 'wp_insert_post_data', 'enforceMinWordCount', 99, 2 );
    

    This isn't very UX-friendly however, since a user will lose their post and get sent to an error screen. I'd recommended setting the status of the post to pending if it doesn't meet the minimum word count requirements, and notifying the user via the admin_notices hook that it cannot be published until the word count is reached.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥20 求快手直播间榜单匿名采集ID用户名简单能学会的
  • ¥15 DS18B20内部ADC模数转换器
  • ¥15 做个有关计算的小程序
  • ¥15 MPI读取tif文件无法正常给各进程分配路径
  • ¥15 如何用MATLAB实现以下三个公式(有相互嵌套)
  • ¥30 关于#算法#的问题:运用EViews第九版本进行一系列计量经济学的时间数列数据回归分析预测问题 求各位帮我解答一下
  • ¥15 setInterval 页面闪烁,怎么解决
  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历