For an indie rock agenda I created event posts. With the help of javascript, the custom fields values (bands, places and date info picked in select boxes) are copied as the post title when publishing or updating the post.There is also a custom function which update the slug every time the title changes.
Problem: if an other user create a new post picking exactly the same custom fields values, then an other post with exactly the same slug is created.
And if two posts with the same slug are created, both of them lead to a 404 error page until one of them is manually deleted.
My question: is there a way to “validate” the post slug comparing it to the older posts in the database ?
Thanks for your help !
Leave a Reply
You must be logged in to post a comment.
The Ajax way (a little bit dirty, but you can easily enhance it)
In your functions.php (or in a plugin, or every where else) :
And somewhere in your metabox template (or loaded via an action) :
You’d be surprised at how tricky this one turns out to be. Closest I’m getting is hooking into the
save_post
action. There appears to be no action to hook to that will stop the post from saving, all the actions forupdate_post()
andwrite_post()
don’t appear to allow any direct interference; so the very simple and quick option I’ve come up with involves dying inside the hook. Even so, the post is saved with the duplicate name regardless of our dying.The
save_post
action supplies the hook with the post ID of the saved post. Then events are searched for using the ‘s’ argument, just like you would search for using the regular WordPress search on your pages. The events are then iterated through and if a post with an ID other than the checked-upon post is found with a title that matches this checked-upon post then it dies.Something more helpful and less stripped down would involve a custom message when the post is published.
This is a quick solution, something even more involved would perhaps require that the saved post which has just infringed the no-duplicate-title rule has to have it’s title modified and resaved by the function, turning it into something like ‘DUPLICATE! [the title here]’ and changing post status back to ‘pending’.
The yellow message seems to be quite subtle and may not be noticed by publishers, dying seems to be more attention-grabbing.
Hope this helps and didn’t confuse you too much. There may be better solutions to the problem, let’s hope someone comes by and helps us improve the solution. Any ideas will be appreciated at this point.
Instead of making your own query, why not just using the function post_exists() ?
It takes the post_title, content and date ( optionnal ).
This function does not test the post_type but its rare that you have the same post_title on your content.
Regards,
Rahe.
find if POST Slug already exists: