How to check for duplicate record before saving a Custom Post Type
I have a custom post type where I need to check for a duplicate record before the record actually gets saved into the database.
The requirement is like this: Before saving a record, I need to check whether another record with the currently provided combination of post_title, county (meta field) and city (meta field) exists already.
I have written the function for searching a similar record:
function mbs_check_duplicate_record() {
global $post, $wpdb;
$company = $_REQUEST['post_title'];
$post_type = $_REQUEST['post_type'];
$country = $_REQUEST['txtClientsCountryMbs'];
$city = $_REQUEST['txtClientsCityMbs'];
$args = array(
'post_title' = $company,
'post_type' = $post_type,
'post_status' = 'publish',
'posts_per_page' = 1,
'meta_query' = array(
array(
'key' = '_mbs_clients_country',
'value' = $country,
'compare' = '='
),
array(
'key' = '_mbs_clients_city',
'value' = $city,
'compare' = '='
)
),
);
$dup = new WP_Query( $args );
if( $dup-post_count 0 ) {
return false;
} else {
return true;
}
}
I have also deregistered autosave functionality by adding this:
add_action( 'wp_print_scripts', function(){
wp_deregister_script( 'autosave' );
} );
Then I called the above function inside the function which I am using to hook with save_post
like this:
function mbs_save_clients_meta( $post_id ) {
if(
! isset( $_POST['clients_url_nonce'] ) ||
! isset( $_POST['clients_city_nonce'] ) ||
! isset( $_POST['clients_country_nonce'] ) ||
! isset( $_POST['clients_lat_nonce'] ) ||
! isset( $_POST['clients_lng_nonce'] ) ) {
return;
}
if( ! current_user_can( 'edit_post', $post_id) ) {
return;
}
if( ! mbs_check_duplicate_record() ) {
add_filter( 'admin_notices', function(){
echo 'div id="mbs_duplicate_entry"Client already exists! Please check Name, Country and City./div';
die();
} );
} else {
The save routine starts ...
}
}
add_action( 'save_post', 'mbs_save_clients_meta' );
But the post always gets save even it finds an existing record.
UPDATE
Actually, when a duplicate record is found, no metadata is saving, but a new post is always getting added with the title. How can I prevent WordPress from doing this, i.e., nothing should be saved if another record with the given combination is already existing in the database?
Also, the admin_notices
hook is not displaying my custom message. This is probably because the post is being created?
Topic autosave save-post custom-post-types Wordpress
Category Web