Ask your WordPress questions! Pay money and get answers fast! Comodo Trusted Site Seal
Official PayPal Seal

Find duplicate posts using meta data WordPress

  • SOLVED

Looking for a simple way to find duplicates with a query, I just need to see if two meta fields are exactly equal.

movie_id and movie_status

If both of these are the same for both posts its a duplicate. This is a custom post type called movies if that helps any. I would just run this function every once in a while to find duplicates, it could return IDs then ill pass it to a function I wrote to use the list of IDs to remove the posts.

Answers (2)

2018-04-06

webGP answers:

function get_duplicates() {
$duplicates = array();

$query_all = new WP_Query( array(
'post_type' => 'movies',
'posts_per_page' => -1,
'fields' => 'ids',
) );

$all_posts = $query_all->posts;

foreach ( $all_posts as $post_id ) {

if ( in_array( $post_id, $duplicates ) ) {
continue;
}
$args = array(
'post_type' => 'movies',
'posts_per_page' => -1,
'meta_query' => array(
array(
'key' => 'movie_id',
'value' => get_post_meta( $post_id, 'movie_id', true ),
'compare' => '=',
),
array(
'key' => 'movie_status',
'value' => get_post_meta( $post_id, 'movie_status', true ),
'compare' => '=',
),
),
'post__not_in' => array( $post_id ),
'fields' => 'ids',
);
$query = new WP_Query( $args );
$duplicates = array_merge( $duplicates, $query->posts );
}

array_unique( $duplicates );

return $duplicates;
}


User179751 comments:

Could be a 1000+ posts, not sure how efficient this would be.


webGP comments:

How often do you need to call this action?

2018-04-06

Arnav Joy answers:

please try this one.

<?php
function aj_get_duplicates() {

global $wpdb;

$args = array( 'post_type' => 'movies', 'posts_per_page' => -1 );

$posts = get_posts( $args );
if( $posts as $post_data ){
$post_id = $post_data->ID;

if ( in_array( $post_id, $post_ids_processed ) ) {
continue;
}

$movie_id = get_post_meta( $post_id, 'movie_id', true );
$movie_status = get_post_meta( $post_id, 'movie_status', true );

$post_ids_processed[] = $post_id;

if( $movie_id ){
$result = $wpdb->get_results( "SELECT post_id FROM ".$wpdb->prefix."postmeta WHERE meta_key = 'movie_id' AND meta_value = '".$movie_id."' " );
if( $result ){
foreach( $result as $row ){
$duplicate_ids[] = $row->post_id;
}
}
}

if( $movie_status ){
$result = $wpdb->get_results( "SELECT post_id FROM ".$wpdb->prefix."postmeta WHERE meta_key = 'movie_status' AND meta_value = '".$movie_status."' " );
if( $result ){
foreach( $result as $row ){
$duplicate_ids[] = $row->post_id;
}
}
}

if( !empty( $duplicate_ids ) ){
$duplicate_arr[ $post_id ] = $duplicate_ids;
$post_ids_processed[] = $duplicate_ids;
}

array_unique( $duplicate_arr );

return $duplicate_arr;


}

}