Is there a way (via routing) in CodeIgniter to change:
example.com/category/4
to example.com/category/foo-bar
where Foo Bar
is the name of category 4
in the database?
Access from the SEO-friendly URL should be allowed, but access via the integer should cause a 404 error.
This should also work dynamically, where any integer is automatically converted to a URL-safe version of its corresponding category name.
I've seen a few solutions that use 'slugs'... is there a decent alternative?
Thanks.
I've only been working with CodeIgniter for the past couple of months in my spare time, so I'm still learning, but I'll take a shot at this (be gentle):
There is a url_title()
function in the URL Helper (which will need loaded, of course) that will change Foo Bar
to foo-bar
.
$name = 'Foo Bar';
$seo_name = url_title($name, TRUE);
// Produces: foo-bar
http://codeigniter.com/user_guide/helpers/url_helper.html
The URL helper strips illegal characters and throws in the hyphens by default (underscores, by parameter) and the TRUE
parameter will lowercase everything.
To solve your problem, I suppose you could either do a foreach
statement in your routes.php file or pass the url_title()
value to the URL, rather than the ID, and modify your code to match the url_title()
value with its category name in the DB.