Using slugs in codeigniter

倖福魔咒の 提交于 2019-11-27 12:29:39

I just store the slugs in my database table, in a column called slug, then find a post with the slug, like this:

public function view($slug)
{
    $query = $this->db->get_where('posts', array('slug' => $slug), 1);

    // Fetch the post row, display the post view, etc...
}

Also, to easily derive a slug from your post title, just use url_title() of the URL helper:

// Use dashes to separate words;
// third param is true to change all letters to lowercase
$slug = url_title($title, 'dash', true);

A little bonus: you may wish to implement a unique key constraint to the slug column, that ensures that each post has a unique slug so it's not ambiguous which post CodeIgniter should look for. Of course, you should probably be giving your posts unique titles in the first place, but putting that in place enforces the rule and prevents your application from screwing up.

You can use the CI Slug Library by Eric Barnes:

https://github.com/ericbarnes/CodeIgniter-Slug-Library

To my ES friends, remove accented characters using this, from Text Helper:

    $string = 'áéíóú ÁÉÍÓÚ';    
    $slug = url_title(convert_accented_characters($string), 'dash', true));
    echo $slug; //aeiou-AEIOU
Hafiz Adil

Creating Page slug in codeigniter

create Helper with the name of slug_helper.php

<?php

if (!function_exists('create_slug')) {
function create_slug($string)
{
    $slug = trim($string);
    $slug = strtolower($slug);
    $slug = str_replace(' ', '-', $slug);

    return $slug;
} } ?>


autoload
$autoload['helper'] = array('slug');

 Controller
 $data = array(
            'title' => $this->input->post('title'),
            'content' =>$this->input->post('content'),
            'slug' => create_slug($this->input->post('title'))
        ); 

 $insert_page = $this->Admin_model->insert_page($data);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!