CakePHP - generate unique slug


/ Published in: PHP
Save to your folder(s)

this method generates and returns a unique slug, given a string.


Copy this code and paste it in your HTML
  1. /**
  2.  * genera uno slug unico per le ricerche e i fancy url
  3.  * @param $string {string} stringa da trasformare in slug
  4.  * @return $slug {string} uno slug valido (yyy-yyyyyy-yyy), appende un numero alla fine per renderlo unico
  5.  */
  6. public function __to_slug($string) {
  7. $slug = strtolower(Inflector::slug($string, '-'));
  8. $count = $this->find( 'count', array(
  9. 'conditions' => array(
  10. $this->alias . ".slug REGEXP" => "^($slug)(-\d+)?"
  11. )
  12. ));
  13. // genero un url nome-slug-1 -- nome-slug-2
  14. if($count > 0) return $slug . "-" . $count;
  15. else return $slug;
  16. }

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.