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 ); } }
Categories:
Programming
- Wordpress
- Code snippets