CakePHP: Use post title as the slug for view method

后端 未结 4 688
情深已故
情深已故 2020-12-22 06:44

I have been trying to do the following method to create urls like:

domain.com/portfolio/This_is_a_test_post

function view ( $title )
{           


        
相关标签:
4条回答
  • 2020-12-22 07:21

    you can't do that. When saving the post, you should slug the title already; or if you want to keep the title, put the slug to another field to find later.

     function view ( $title = null ){       
       if(!$title)$this->redirect(array('action'=>'index'));
       $post = $this->Portfolio->find('first', array('conditions' => array('Portfolio.title' => $title)));
       $this->set(compact('post'));
     }
    
    0 讨论(0)
  • 2020-12-22 07:23

    you can use this lib support to convert urls without more efforts

    http://someguyjeremy.com/blog/slugs-ugly-bugs-pretty-urls

    0 讨论(0)
  • 2020-12-22 07:30

    It does not work because you are applying the Inflector::slug function to the name of the column.. Try the other way around.., add a slug column to your post, and create the slug when you add the post using the Inflector, try something like this when you add your post:

    $this->data['Post']['slug'] = Inflector::slug($this->data['Post']['title']);
    

    and on your controller, do this:

    function view($slug = null) {
        if (is_null($slug)) {
            $this->cakeError('error404');
        } else {
            $post = $this->Post->findBySlug($slug);
            $this->set(compact('post'));
        }
    }
    

    that should do the trick.. i hope it helps..

    0 讨论(0)
  • 2020-12-22 07:45

    I would recommend using the ID for addressing content on your website, this way you do not have to worry about dealing with title/slug changes. For a SEO perspective you can easily use the Slug without doing anything with it technically:

    function view($id) {
       $this->Post->id = $id;
       $this->set('post',$this->Post->read());
    }
    

    And in your view, create links like this:

    $this->Html->link('name of the link', array('controller' => 'posts', 'action' => 'view', $post['Post']['id'], Inflector::slug($post['Post']['title'])));
    

    Now your URL's will look like this:

    domain.com/posts/13/This_is_a_test_post
    

    Note that the slug isn't doing anything, but is giving you the benefit of SEO

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