How I check if the same post slug has not been used before publishing?

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 Comment