开发者

CakePHP: Use post title as the slug for view method

I have b开发者_开发百科een trying to do the following method to create urls like:

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

However it doesn't show the post! Obviously I'm doing something wrong... Any ideas on how I could fix this? Thanks


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


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..


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


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

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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜