Welcome Guest, Not a member yet? Register   Sign In
news story titles in urls

[eluser]adrian westlake[/eluser]
I have been doing the tutorials, including the one to create a simple blog. At the moment the urls, use the unique id field as the last segment to point to the blog story. However, sites like digg seem to use the title of the story as the last segment in the url. How is this possible, bearing in mind the title is not a unique identifier?

Well, digg uses the title as an unique identifier. When a title already exists within a certain category, they append a number.

Same thing can be done with CI, just a matter of routing your category and for instance saving the URI-title along with the real title.


actually I do it like this (I'm a beginner, so, it's not sure that this is the best way to answer your problem)

$route['yourcontroller/([0-9]+)(_[a-zA-Z0-9-]*)?'] = "yourcontroller/yourshowingmethod/$1";

And, on my views:
<?=anchor("yourcontroller/".$row->id."_".url_title($row->title), $row->title)?>

Examples :
yourcontroller/ -> list of elements
yourcontroller/5 -> element with id = 5
yourcontroller/5_my-title -> element with id = 5 with its title on the URL
yourcontroller/5_a-fake-title -> works too and get element with id = 5 too but not really matter Wink

I wish I answer your question...


CI has a built-in converter, url_title() that takes your title as a parameter and returns "friendly" url:
$title = 'The Greatest Blog Post ever(tm)';
$urltitle = url_title($title); // returns 'the-greatest-blog-post-ever-tm'
You then save this url in your database together with your blog (or news, or whatever) post, and when it's called you search for that string and return that post.
// Assuming the called URL is something like news/show/the-greatest-blog-post-ever-tm/
$title = $this->uri->segment(3);
$q = $this->db->getwhere('blog', array('urltitle' => $title));
// Show it
I hope this helps clarify it

[eluser]adrian westlake[/eluser]
Thanks Flayra,

Does this assume that the title is a unique field?



..these url "titles" are known as slugs (might help with finding tutorials). And you as the programmer must ensure that they are unique.

[eluser]adrian westlake[/eluser]
Great, so I do something like the following (pseudocode)?

$urltitle = url_title($title)
$title = $this->uri->segment(3);
$q = $this->db->getwhere('blog', array('urltitle' => $title));
   //insert record into database with $urltitle as the title field
   //insert record into database with $urltitle appended with a unique number
   $urltitle = $urltitle."_".($this->db->num_rows()+1);

As batteries said, the field needs to be unique to positively identify. An often used technique is simply adding the date before or after the title since it's unlikely you post a blog with the same title twice on the same day - an example title would be: 06-12-blog-post-about-something-exciting.

Theme © iAndrew 2016 - Forum software by © MyBB