Friendly Slug Custom Field (WordPress Style)

Description

SEO-friendly URLs are a must-have nowadays. They not only help web pages rank better in search engines, but also help site visitors and content managers quickly identify a page by glancing over the URL. Generating a slug, a common type of SEO-friendly URL, is a relatively easy task with JavaScript: just change all non-alphanumeric characters to dashes and remove any double-dashes (for example, "Yes: This is the best blog *ever*!!" becomes "yes-this-is-the-best-blog-ever"). Sometimes, however, a slug may turn out the same as one that is already in use, which would cause a page to have a duplicate URL! For instance, a page titled "Exceptional: New Series" would have the same slug as "Exceptional New Series!" ("exceptional-new-series"). The most common way to solve this problem, as made popular by the WordPress content management system, is to check whether a slug already exists and if so, add a number to the end (e.g., "exceptional-new-series-2"). The question for dotCMS developers then becomes, how can one check for duplicate slugs as new content is created in the administration page? This article explains how to accomplish this task.

Although this version only accepts one field, it can be easily modified to generate slugs using two or more fields (e.g., year-month-title) by adding additional $customVarSource variables and appending them together in the old_slug variable declaration in the updateDisplay() JavaScript function of the custom field code. Other modifications may include support for international characters (e.g., converting an e with acute, é, to an e), using a character other than dashes to separate words, and support for more than 999 duplicates. Thus, this code can be used as is, or as the basis for further enhancements that can satisfy more specific business requirements.

This article was published on my blog at: http://gabriel.mongefranco.com/2012/03/friendly-slug-custom-field-for-dotcms/