Question

I'm new to Wordpress. I created a custom post type in a plugin and I'm trying to add a custom validation to it.

Before saving a new post of this type (in admin), I'd like to check if the submitted post title already exists. So that's what I thought it could be:

  • User fills the form and submits it;
  • Before saving (in a hook), the submitted title is searched in the database for the same title and the same post type;
  • If some entry is found, the post is prevented from saving, an error message is defined and the browser is redirected to the post form, pre-filled with the submitted data. And the error message is shown to the user.
  • If no entry is found, the flow is not interrupted and the post is normally saved.

Is this logic correct? If not, how should it be?

As I'm new to Wordpress, I'm not using a OOP approach, at least not yet.

Thanks!

Was it helpful?

Solution

Well, it seems that my proposed logic is invalid.

Also, looks like the only way of preventing a post being saved is if you validate the form using JavaScript.

The closer answer I could find is this one. And yet it doesn't cover validation if the user is quick editing the post.

So, again, using JavaScript for validation seems to be the best option - at least in this case, which does not contain a more complicated field like a file upload.

Thanks for helping!

EDIT: The Duplicate Title Checker plugin gives an idea on how to do it with JS.

OTHER TIPS

I used Duplicate Title checker and in duplicate-title-checker.php I changed line 34 from...

$sim_titles = "SELECT post_title FROM $wpdb->posts WHERE post_status = 'publish' AND post_type = 'post' AND post_title = '{$title}' AND ID != {$post_id} ";

to...

$sim_titles = "SELECT post_title FROM $wpdb->posts WHERE post_status = 'publish' AND post_title = '{$title}' AND ID != {$post_id} ";

Seems to do the trick.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top