PHP routing with Codeigniter (Titles in URL for SEO)

后端 未结 3 955
故里飘歌
故里飘歌 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:21

    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

    0 讨论(0)
  • 2021-01-15 04:32

    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.

    0 讨论(0)
  • 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 ;)

    0 讨论(0)
提交回复
热议问题