[Resolved] Issue with duplicate post titles when editing
This thread is resolved. Here is a description of the problem and solution.
Problem:
The user would like to allow users to create posts, from the frontend, with unique titles. He uses custom code for validation, but the custom code fails for updates as the new title equals the old(existing) one.
Tell us what you are trying to do?
I am implementing code to prevent duplicate post titles. I used a ticket from 2019 and it works great... The problem is that I have an edit form for posts and it won't save changes because the post title is the same as the title of the post you are editing. I could just remove the code from the edit form, but if the user decides to edit the name of the post, they shouldn't be able to use a name that someone else might already have. So, for the edit form, I need to prevent duplicate post titles but disregard the name of the post they are editing.
Of course. Here is what I added for the post creation form and the post edit form:
/* Validate CRED Forms */
add_filter('cred_form_validate','func_validate_title',10,2);
function func_validate_title($error_fields, $form_data){
list($fields,$errors)=$error_fields;
$forms_array = array( 20, 23 );
if (in_array($form_data['id'], $forms_array)) {
// get the title from the form
$title = $_POST['post_title'];
// query to get the posts to compare
$args = array( "post_type" => "crowd", "posts_per_page" => -1, "post_status" => array('publish', 'draft') );
$query = get_posts( $args );
if (count($query) > 0){
//set error message for the title field if a post of the same title exists
foreach ($query as $post) {
if (strtolower($post->post_title) == strtolower($title)) {
$errors['post_title']='Duplicate Title! Add another!';
break;
}
}
}
}
//return result
return array($fields,$errors);
}
You will need to pull the current title from the database and compare it to the newly typed title. Put the following code at line 10:
// get post_id
$post_id = $form_data['container_id'];
// get the post
$post = get_post( $post_id );
// If title is the same return, otherwise continue
if ( $post->post_title == $_POST['post_title']) return array($fields,$errors);