PHP WordPress Delete Duplicate Post By Title And Category

PHP WordPress Delete Duplicate Post By Title And Category

I have been looking online for a code solution that is able to check through specific categories for duplicate posts and never been able to found a solution good enough for me. Solutions online were slow and memory-consuming which was a major reason why I couldn’t use them. So I wrote my own.

For the code below to work, you need to ensure that you sort your posts in alphabetical order. The logic is that you have a inner-loop that checks from the given post (Post A) till the last post for any duplicate titles. The logic at the same time ensures that Post A will never be deleted, ensuring you have at least 1 copy of the post.

$args = [
    'post_type'     => 'post',
    'post_status'   => 'publish',
    'category_name' => $category->name,
    'orderby'   => 'post_title', 
    'order' => 'ASC',
    'post_per_page' => -1,
    'nopaging' => true,
];
$my_query = new WP_Query( $args );
$posts = $my_query->posts;

    $num_of_posts = count($posts);
    echo "category : {$category->name} <br/>";
    echo "num_of_posts : {$num_of_posts} <br/>";
    
    for($j = 0; $j < $num_of_posts; $j++)
    {
        $post = $posts[$j]; // this post will be the post that doesnt get deleted, if any duplicates exist down the line //
        $current_title = $post->post_title;
        
        for($k = $j+1; $k < $num_of_posts; $k++)
        {
            $next_post = $posts[$k];
            $next_title = $next_post->post_title;
            $next_id = $next_post->ID;
            
            if( strcmp($current_title, $next_title) == 0 ) {
                echo "Duplicate for {$current_title} with ID {$next_id} will be deleted <br/>";
                wp_delete_post($next_id, false); // move to trash first
            }
        }
    }	
}

 

Enjoyed the content ? Share it with your friends !