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 !

4 Answers
4

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) :

function my_ajax_update(){
    if (isset($_POST['title'])){
        global $wpdb;
        $title = esc_sql($_POST['title']);
        if(!$title) return;
        $page = $wpdb->get_results("
            SELECT *
            FROM $wpdb->posts
            WHERE post_title LIKE '$title'
            AND post_type="event"
            AND post_status="publish"
            LIMIT 1
        ");
        if ($page) echo "This title already exists !";
    }
}
add_action("wp_ajax_check_double_post", "my_ajax_update");

And somewhere in your metabox template (or loaded via an action) :

jQuery(document).ready(function($){
    var the_title = $('#title').val();
    $('#publish').click(function(e){
        e.preventDefault();
        $.post(
            ajaxurl,
            {
                action:"check_double_post",
                title: the_title
            },
            function(data){
                if ((data) != 0) {
                    message = $('<div id="message" class="error below-h2" />').html('<p>Warning, this title already exists!</p>')
                    $('h2').after(message);
                    $('#ajax-loading').hide();
                    $('#publish').removeClass('button-primary-disabled');
                }
                else {
                    $(this).submit();
                }
            }
        );
    });
});

Leave a Reply

Your email address will not be published. Required fields are marked *