CakePHP:使用帖子标题作为视图方法的slug

Cam*_*ron 0 cakephp

我一直在尝试使用以下方法来创建网址:

domain.com/portfolio/This_is_a_test_post

function view ( $title )
{       
    $post = $this->Portfolio->find('first', array('conditions' => array(Inflector::slug('Portfolio.title') => $title)));

    //$posts = $this->Portfolio->title = Inflector::slug($title);

    if (empty($title))
    {
        $this->cakeError('error404');
    }
    else
    {
        $this->set(compact('post'));
    }
}
Run Code Online (Sandbox Code Playgroud)

但它没有显示帖子!显然我做错了什么......关于如何解决这个问题的任何想法?谢谢

bo-*_*-oz 5

我建议使用该ID来寻址您网站上的内容,这样您就不必担心处理标题/ slug更改了.对于SEO视角,您可以轻松地使用Slug,而无需在技术上做任何事情:

function view($id) {
   $this->Post->id = $id;
   $this->set('post',$this->Post->read());
}
Run Code Online (Sandbox Code Playgroud)

在您的视图中,创建如下链接:

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

现在您的网址将如下所示:

domain.com/posts/13/This_is_a_test_post
Run Code Online (Sandbox Code Playgroud)

请注意,slug没有做任何事情,但是给了你SEO的好处

  • 这应该在没有检查`view()`动作中slug的有效性的情况下使用,因为你冒险创建一个页面的无限量的URL,这可能是SEO的自杀(改变SO中的slu and你会看到它重定向到右边) (3认同)