How to check if a slug exists?

This is what you’re looking for, tested and I use it on my own sites:

function the_slug_exists($post_name) {
    global $wpdb;
    if($wpdb->get_row("SELECT post_name FROM wp_posts WHERE post_name="" . $post_name . """, 'ARRAY_A')) {
        return true;
    } else {
        return false;
    }
}

You can then use it like this:

if (the_slug_exists('contact')) {
    // do something
}

Replace contact with whatever slug you want to test for.

Leave a Comment