如果我们在编辑文章的时候,尤其是多用户编辑的时候可能会导致文章的标题重复。这里我们可以用插件和代码实现检测是否有重复的文章,如果有的话提示。
add_action( 'admin_print_footer_scripts', 'duplicate_titles_enqueue_scripts', 100 ); function duplicate_titles_enqueue_scripts() { ?> <script> jQuery(function($){ function checkTitleAjax(title, id,post_type) { var data = { action: 'title_checks', post_title: title, post_type: post_type, post_id: id }; $.post(ajaxurl, data, function(response) { $('#message').remove(); $('#poststuff').prepend('<div id=\"message\" class=\"updated below-h2 fade \"><p>'+response+'</p></div>'); }); }; $('#title').change(function() { var title = $('#title').val(); var id = $('#post_ID').val(); var post_type = $('#post_type').val(); checkTitleAjax(title, id,post_type); }); }); </script> <?php } add_action('wp_ajax_title_checks', 'duplicate_title_checks_callback'); function duplicate_title_checks_callback(){ global $wpdb; $title = $_POST['post_title']; $post_id = $_POST['post_id']; $titles = "SELECT post_title FROM $wpdb->posts WHERE post_status = 'publish' AND post_type = 'post' AND post_title = '{$title}' AND ID != {$post_id} "; $results = $wpdb->get_results($titles); if($results) { echo "<span style='color:red'>". _( '存在重复标题!' , '' ) ." </span>"; } else { echo '<span style="color:green">'._('标题不重复!' , '').'</span>'; } die(); } add_action( 'publish_post','duplicate_titles_wallfa_bc' ) ; function duplicate_titles_wallfa_bc( $post ){ global $wpdb ; $title = $_POST['post_title'] ; $post_id = $post ; $wtitles = "SELECT post_title FROM $wpdb->posts WHERE post_status = 'publish' AND post_type = 'post' AND post_title = '{$title}' AND ID != {$post_id} " ; $wresults = $wpdb->get_results( $wtitles ) ; if ( $wresults ){ $wpdb->update( $wpdb->posts, array( 'post_status' => 'draft' ), array( 'ID' => $post ) ) ; $arr_params = array( 'message' => '10', 'wallfaerror' => '1' ) ; $location = add_query_arg( $arr_params , get_edit_post_link( $post , 'url' ) ) ; wp_redirect( $location ) ; exit ; } } add_action( 'admin_notices', 'not_published_error_notice' ); function not_published_error_notice() { if(isset($_GET['wallfaerror']) == 1 ){ ?> <div class="updated"> <p style='color:red' ><?php _e('文章标题重复!' , '') ?></p> </div> <?php } } // 禁用自动保存 add_action( 'wp_print_scripts', 'disable_autosave' ) ; function disable_autosave(){ wp_deregister_script( 'autosave' ) ; }
这样我们发布的文章标题会检测是否重复。
评论