Codeigniter friendly URL with emphasis on SEO

0

Friends, I'm developing a blog on CI. And thinking about the SEO of the blog, I would like the URL rather than be presented this way:

  

link

I would like it to appear with the title of the post.

  

link

My Route looks like this:

$route['blog/(:num)'] = "blog/postagem/$1";

My controller is like this (do not worry about gambiarra, so I solve this issue of SEO I create the Models correctly):

class Blog extends CI_Controller {

    public function postagem($id){
        $this->db->where('id', $id);
        $data['blog'] = $this->db->get('blog')->result();
        $this->load->view('site/blog/postagem', $data);
    }
    public function home(){
        $data['blog'] = $this->db->get('blog')-> result();
        $this->load->view('site/blog/home' , $data);
    }

View post:

<?php foreach ($blog as $post ) { ?>
    <h1><?php echo $post->titulo; ?>- <small><?php echo $post->categoria;?></small></h1>
    <p><?php echo $post->texto;?></p>
    <hr>
    <?php } ?>

View Home:

<?php foreach ($blog as $post ) { ?>
    <a href="<?php echo site_url('blog/postagem');?>/<?php echo $post->titulo; ?>"><?php echo $post->titulo?></a>
    <hr>
    <?php } ?>

I would like to know how the CI will actually identify that the title in the url corresponds to an ID on the Route .. I can not understand, can anyone help me?

    
asked by anonymous 12.02.2018 / 00:54

2 answers

1

I believe one of the requirements for you to find your answer is to understand how CodeIgniter interprets URLs .

The representation would look like this:

dominio.com.br / classe / método / IDs e outros parâmetros

So, when you go to: link , the Controller class Blog is loaded and the postagem method is executed, receiving the parameter 1 via GET .

In the code is exactly what you already have:

<?php
    class Blog extends CI_Controller
    {

        public function postagem($id)
        {
            ...
        }
    }

Now, when you use routes, you're "masking" it. Internally, everything works the same way, but the URI is treated differently, that is, CodeIgniter remaps before execution.

If you want to turn your URL into something like this: link , you will have to configure the route as follows:

$route['blog/(.+)'] = 'blog/postagem/$1';

And then, in the postagem method, the parameter that will be the title of the post will be able to follow the way that @Phelipe suggested.

Sources:

link

link

    
12.02.2018 / 01:47
0

You can use the url_title () function. The function takes a string as input and creates a friendly URL string. You take the title of your post and go through this function and use it as part of the URL. You save this part of the url in your database and when searching in your database for news, you do not do ID , but for that part of the url.

I suggest reading an example that Codeigniter's own documentation brings back from implementing a news site. You can find this example here

    
12.02.2018 / 01:09