Question

How can I check if a slug already exists in my WordPress database?

I'd like to check any slug (post, page, taxonomies and custom post type/taxonomies)

thanks

Was it helpful?

Solution

http://codex.wordpress.org/Function_Reference/wp_unique_post_slug has the answer. If you use it giving it the desired slug, it will return one that truly is unique.

OTHER TIPS

I just answered this over here: https://wordpress.stackexchange.com/questions/25940/how-to-check-if-a-slug-exists/144439#144439

Not sure what the policy on duplicate answers is, but here you go:

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.

Use WP_Query():

$args = array(
  'post_type'    => 'custom-post-type',
  'name' => 'my-new-slug'
);

$query = new WP_Query($args);

if ($query->post_count == 0) {
  // I am unique!
}

In general, WP_Query() prevents the need for direct DB calls and makes your site more maintainable.

<?php
    $url = $_SERVER["REQUEST_URI"];
    $isItYourSlug = strpos($url, 'your_slug');

    if ($isItYourSlug!==false) {
        Do Something
    }
?>

It ok? It work for me!

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top