wp_unique_term_slug

Definition:
function wp_unique_term_slug($slug, $term) {}

Will make slug unique, if it isn’t already.
The $slug has to be unique global to every taxonomy, meaning that one taxonomy term can’t have a matching slug with another taxonomy term. Each slug has to be globally unique for every taxonomy.

Parameters

  • string $slug: The string that will be tried for a unique slug
  • object $term: The term object that the $slug will belong too

Return values

returns:Will return a true unique slug.

Source code

function wp_unique_term_slug($slug, $term) {

	global $wpdb;



	if ( ! term_exists( $slug ) )

		return $slug;



	// If the taxonomy supports hierarchy and the term has a parent, make the slug unique

	// by incorporating parent slugs.

	if ( is_taxonomy_hierarchical($term->taxonomy) && !empty($term->parent) ) {

		$the_parent = $term->parent;

		while ( ! empty($the_parent) ) {

			$parent_term = get_term($the_parent, $term->taxonomy);

			if ( is_wp_error($parent_term) || empty($parent_term) )

				break;

			$slug .= '-' . $parent_term->slug;

			if ( ! term_exists( $slug ) )

				return $slug;



			if ( empty($parent_term->parent) )

				break;

			$the_parent = $parent_term->parent;

		}

	}



	// If we didn't get a unique slug, try appending a number to make it unique.

	if ( !empty($args['term_id']) )

		$query = $wpdb->prepare( "SELECT slug FROM $wpdb->terms WHERE slug = %s AND term_id != %d", $slug, $args['term_id'] );

	else

		$query = $wpdb->prepare( "SELECT slug FROM $wpdb->terms WHERE slug = %s", $slug );



	if ( $wpdb->get_var( $query ) ) {

		$num = 2;

		do {

			$alt_slug = $slug . "-$num";

			$num++;

			$slug_check = $wpdb->get_var( $wpdb->prepare( "SELECT slug FROM $wpdb->terms WHERE slug = %s", $alt_slug ) );

		} while ( $slug_check );

		$slug = $alt_slug;

	}



	return $slug;

}

4195

Advertisements

No comments yet... Be the first to leave a reply!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: