Wordpress- create uniqe slug based on title for custom table

If you need uniqe slug for your plugin's or theme's custom table, you can use this Wordpress "style" function.

If slug created matches some earlier slug- it creates new one adding suffix like "-2", "-3" and so on. Everything should be pretty straight forward if you look at code and comment.

/**
 * Create uniqe slug based on title for custom table in Wordpress
 *
 * If slug match found in table
 * it adds iteration value to the end of slug
 * generating slugs like title-1, title-2, title-x
 * looping until found uniqe slug
 *
 * $idField field is used because on modify-
 * we need to exclude current record
 *
 * @param string $tblName Table name
 * @param string $slugField Slug field name to check against
 * @param string $idField ID/uniqe field for ID check
 * @param string $title Title to be used
 * @param int $id ID if updtaing record
 * @param int $cnt Iteration count
 * @return Object
 */
function getUniqeSlugForCustomTable(
  $tblName, $slugField, $idField, $title, $id = 0, $cnt = 1
  ) {
  global $wpdb;

  $startSlug = sanitize_title( $title, md5(time()) );

  if($cnt > 1){
    $startSlug = $startSlug . '-' . $cnt;
  }

  $cnt++;

  $checkSql = "
    SELECT
      `" . $tblName . "`.`" . $slugField . "`
    FROM
      `" . $tblName . "`
    WHERE
      `" . $tblName . "`.`" . $slugField . "` = %s AND
      `" . $tblName . "`.`" . $idField . "` != %d
    LIMIT
      1
  ";

  $check = $wpdb->get_var(
    $wpdb->prepare( $checkSql, $startSlug, $id )
  );

  if(!$check){
    return $startSlug;
  } else {
    return getUniqeSlugForCustomTable(
      $tblName, $slugField, $idField, $title, $id, $cnt
    );
  }
}
  

No gravatar aivable
leah melda #
Online Biology Paper Writing Services produces different assignments, including Buy Essay Online Services, to help students deal with the Buy Business Reports challenges they face every day.
No gravatar aivable
leah melda #
All Academic Custom College Paper Writing Services shall deliver your Article Review Papers Services on time without compromising on the Custom Thesis Writing Service quality.
No gravatar aivable
King #
King http://gosuslugi.ru
I am co-founder of web/media studio GIVE me. and (android)developer at start-up named Choco. Read my about page to learn more.