PHP routing with Codeigniter (Titles in URL for SEO)

天涯浪子 提交于 2019-12-01 10:39:44

I have done something similar in the past; I can't find it know but IIRC (it was months ago) You can use a route like you did, and also add a more specific one, like

$route['articles/(:num)/(:any)'] = 'articles/view/$1/$2';
$route['articles/(:num)'] = 'articles/view/$1';

As you can see, both map to the same method, which is kind of "overloaded"; you can make up for a missing parameter by using a default value:

function articles($id,$slug = FALSE) 
{ }

and simply ignore the second parameter in your article retrieval.

As for adding the title you can:

  1. have a "slug" field in your database, created when the article is saved. You can use the comfortable url_title($title,'dash',TRUE) function (in the url helper), which takes the $title, uses the dash as separator, and make it all lowercase;
  2. use the above function and convert the title of the article (after you retrieved it from the database) "on-the-fly"; just check on the article() method if the 2nd parameter isn't false and you'll know if you need to create the slug or not;

As for how to show the slug even when using an url without it you can make, as you guessed, a redirect, but since both routes point to the same method it won't change anything for you.

Oh, uhm, beware of loops while calling the redirect, check carefully ;)

I suggest you to create a slug field into your table and complete it with the url you want to use as id. Let me explain.

You have this table

id
title
slug

when you save an article into your db you can dinamically create a slug, for example:

id: 1
title: My first post
slug: 1-my-first-post

then you can use the slug (in this case 1-my-first-post) ad id for the page, you can call it:

www.example.com/articles/1-my-first-post

obviusly you need to handle it in your db slect

As we discussed on the comments.

You can create a route several times and with different parameters each, like:

$route['articles/(:num)/(:any)']
$route['articles/(:num)']

I would create a function with a redirect, adding or not the title to it.

Hope it helps.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!