How to check if a slug exists?

I have a arbitrary string and want to check if a post with that slug string exists in the site. I tried to find a way to list all slugs, but can’t find such a thing. Thanks

5

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