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

如何避免WordPress重复发文?实现标题查重拦截功能

解决WordPress重复标题文章插入的问题

嘿,别担心,这个需求其实很好实现,核心思路就是先检查数据库里有没有相同标题的文章,再决定是否执行插入。我给你一步步拆解,代码都是新手友好的:

第一步:写一个检查标题是否存在的函数

我们可以用WordPress自带的get_page_by_title()函数快速验证,不过要注意它默认只查页面(page类型),所以得明确指定查文章(post类型):

function post_title_exists($title) {
    // 检查指定标题的文章,限定类型为post
    $existing_post = get_page_by_title($title, OBJECT, 'post');
    // 返回结果:如果对象不为空,说明标题已存在
    return $existing_post !== null;
}

如果需要更严谨(比如覆盖草稿、待审、已发布等所有状态的文章),可以用WP_Query来查询,效率也不错:

function post_title_exists($title) {
    $query_args = array(
        'post_type'      => 'post',
        'post_status'    => array('publish', 'draft', 'pending'), // 包含所有文章状态
        'title'          => $title,
        'posts_per_page' => 1, // 只要找到一篇重复的就够了
        'no_found_rows'  => true, // 关闭总数量统计,优化查询速度
        'fields'         => 'ids' // 只返回文章ID,减少数据传输
    );
    
    $existing_posts = new WP_Query($query_args);
    // 如果查询到结果,说明标题已存在
    return $existing_posts->have_posts();
}

第二步:封装插入逻辑的自定义函数

接下来把检查和插入逻辑整合到一起,这样你调用的时候就非常方便:

function insert_post_if_not_exists($post_data) {
    // 先执行标题检查
    if (post_title_exists($post_data['post_title'])) {
        // 标题重复,返回提示(你也可以改成静默跳过,不输出内容)
        return "标题「{$post_data['post_title']}」已存在,跳过插入";
    } else {
        // 标题不重复,执行插入操作
        $post_id = wp_insert_post($post_data);
        
        // 处理插入结果:成功返回ID,失败返回错误信息
        if (is_wp_error($post_id)) {
            return "插入失败:" . $post_id->get_error_message();
        } else {
            return "文章插入成功,ID:{$post_id}";
        }
    }
}

第三步:使用这个函数插入文章

最后,你只需要准备好文章数据,调用这个自定义函数就行:

// 准备要插入的文章信息,根据你的需求修改
$my_new_post = array(
    'post_title'    => '我的第一篇测试文章',
    'post_content'  => '这里是文章的具体内容',
    'post_status'   => 'publish', // 可选:publish(发布)、draft(草稿)、pending(待审)
    'post_author'   => 1, // 替换成你的作者ID(管理员ID一般是1)
    'post_type'     => 'post'
);

// 执行插入并获取结果
$insert_result = insert_post_if_not_exists($my_new_post);

// 调试用:输出结果(上线后可以去掉这行)
echo $insert_result;

一些额外提醒

  • 如果是批量插入文章,只需要把上面的代码放到循环里,每篇文章调用一次insert_post_if_not_exists()就行。
  • 如果需要忽略标题的大小写(比如「测试文章」和「测试文章」视为重复),可以修改查询逻辑,用posts_where过滤器做不区分大小写的匹配,不过新手先把基础版本跑通就好。
  • 记得把这些代码放到你的主题functions.php文件里,或者自定义插件中,绝对不要直接修改WordPress核心文件!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 03:52:29