PHP routing with Codeigniter (Titles in URL for SEO)

后端 未结 3 977
故里飘歌
故里飘歌 2021-01-15 04:10

I have some questions concering routing with Codeigniter. What I´m doing now is the following:

$route[\'articles/(:num)\'] = \'articles/view/$1\'; // $1 will         


        
3条回答
  •  春和景丽
    2021-01-15 04:36

    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 ;)

提交回复
热议问题