学习定有收获
努力成为大神

WordPress禁止重复文章发布教程及代码

WordPress 原创插件 国人习惯、简约实用、容易上手【点击了解】

//当用户尝试发布重复文章时,系统会阻止发布并显示错误信息
//大神建站--DSDISS.COM
function prevent_duplicate_posts( $data, $postarr ) {
    if ( $data['post_type'] == 'post' && $data['post_status'] == 'publish' ) {
        $existing_posts = get_posts( array(
            'post_type'      => 'post',
            'post_status'    => 'publish',
            'posts_per_page' => -1,
            'fields'         => 'ids',
            'meta_query'     => array(
                array(
                    'key'     => '_duplicate_check',
                    'value'   => md5( $data['post_content'] ),
                    'compare' => '=',
                ),
            ),
        ) );

        if ( ! empty( $existing_posts ) ) {
            if ( isset( $postarr['ID'] ) ) {
                $existing_ids = array_diff( $existing_posts, array( $postarr['ID'] ) );
                if ( ! empty( $existing_ids ) ) {
                    wp_die( '抱歉,此文章内容已存在,不能重复发布。', '重复文章', array( 'response' => 400 ) );
                }
            } else {
                wp_die( '抱歉,此文章内容已存在,不能重复发布。', '重复文章', array( 'response' => 400 ) );
            }
        }

        update_post_meta( $postarr['ID'], '_duplicate_check', md5( $data['post_content'] ) );
    }

    return $data;
}
add_filter( 'wp_insert_post_data', 'prevent_duplicate_posts', 10, 2 );   

function文件放进去上面代码就会提示“抱歉,此文章内容已存在,不能重复发布”!

内容仅供参考:大神建站 - WordPress插件开发 » WordPress禁止重复文章发布教程及代码

评论 3

  1. #-9

    文章解决大问题,作者是 “智慧之星”!

  2. #-8

    分享太精彩,作者是 “文字艺术家”!

  3. #-7

    打卡,好文错过悔一年,别犯傻!

登录

找回密码

注册