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

Related posts

Leave a Reply

5 comments

  1. 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.

  2. How about this simpler approach?

    $post_exists = get_page_by_path( $slug, OBJECT, $post_type );
    if ( ! $post_exists )
        echo 'No post exists with this slug.';
    

    If a post doesn’t exist for the given slug and post type provided then get_page_by_path() returns null.

  3. $args = array('name' => $slugName, 'post_type' => $postType); 
    
    $slug_query = new WP_Query($args);
    echo "<pre>";
    var_dump($slug_query);
    exit;
    

    You then have more than enough information to test if a post was returned or not, hope this helps.

  4. $your_slug = 'my-pageeeeeee';
    $wpdb = $GLOBALS['wpdb'];
    
    
    
    //==================FIRST method======================
        $id = $wpdb->get_var($wpdb->prepare("SELECT ID FROM " . $wpdb->posts . " WHERE post_name = '%s' AND ( post_type = 'page' OR post_type = 'post') ", $slug) );
        if (!empty($id)) {
            //............
        }
    
    
    
    
    
    //====================SECOND method======================
        $counts = $wpdb->get_var($wpdb->prepare("SELECT count(post_name) FROM ".$wpdb->posts ." WHERE post_name like '%s'", $slug) );
        if ($counts >=1 ) {
            //.............
        }