WordPress重复标题处理:新增文章时自动追加Post ID代码优化需求
Fix: Auto Append Post ID to Duplicate WordPress Post Titles
Hey there! Your existing code only handles empty titles, so let's extend it to check for duplicate titles and append the post ID when a match is found. Here's the updated solution that works exactly as you need:
Updated Code
add_filter('title_save_pre', 'auto_append_id_on_duplicate_title'); function auto_append_id_on_duplicate_title($title) { global $post; // Only target 'post' type, skip if title is empty if (empty($title) || get_post_type($post) !== 'post') { return $title; } $current_post_id = isset($post->ID) ? $post->ID : 0; // Query to check for duplicate published posts with the same title (exclude current post) $duplicate_query = new WP_Query([ 'post_type' => 'post', 'post_status' => 'publish', 'title' => $title, 'post__not_in' => [$current_post_id], 'posts_per_page' => 1, 'no_found_rows' => true, // Optimize query speed 'update_post_meta_cache' => false, 'update_post_term_cache' => false, ]); // Append post ID if duplicate exists if ($duplicate_query->have_posts()) { $post_id = get_the_ID() ?: $current_post_id; $title = $title . ' - ' . $post_id; } wp_reset_postdata(); // Clean up query data return $title; }
Key Details Explained
- Duplicate Detection: We use
WP_Queryto scan for published posts with an identical title, excluding the current post to avoid false positives when editing existing content. - Performance Tweaks: Added query optimizations like
no_found_rowsto speed up the check—since we only need to know if at least one duplicate exists, we don't need full pagination data. - Targeted Scope: The code only runs for standard 'post' types; adjust
get_post_type($post) !== 'post'if you need this for custom post types too. - Edge Case Handling: Accounts for both new and existing posts by checking if
$post->IDis set, ensuring we always grab the correct post ID to append.
Example
If you already have a post titled "the best sandwich", creating a new post with the same title (and assigned post ID 216) will automatically update the new post's title to "the best sandwich - 216".
内容的提问来源于stack exchange,提问作者omid mirzaei
相关产品推荐
相关产品推荐

