Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make a post slug unique

Tags:

php

slug

I got few functions in placed which is not working as I wanted.

The slug is automicatlly created on the fly depend on the post title.

Example: If a post title is "test" then the slug will be "test"

My problem is that, what if theirs duplicate entry of post title "test" which means that the slug will be duplicated too. For that reason I have create 2 functions to handle this for me.

This function checks if the slug exist in the database

function slug_exist($x){
    global $db;
        $sql = "SELECT post_name FROM posts WHERE post_name=\"$x\"";
        $query = $db->select($sql);
            if($db->num_rows() > 0){
                return true;
    }
}

If the slug does exist in the database then am using this function to give the slug a unique name

    if(slug_exist($slug)){
        $rand = rand(10,50);
        $slug = $slug."-".$rand;
            return $slug;
    }

Well when the slug will get unique slug name it will be like Example: test-244

I want the slugs to be in numeric order and not in random order.

**Example:**

Post Title is "Test"
Slug is "test-1"

Post Title is "Test"
Slug is "test-2"

Post Title is "Test"
Slug is "test-3"

This is the only way I know how to explain in detail please let me know if you are not sure what am taking about. Thanks!

like image 455
Johny Avatar asked Dec 07 '13 09:12

Johny


People also ask

Should slugs be unique?

Page slugs must be unique within their own trees. Pages are in a separate namespace than posts so page slugs are allowed to overlap post slugs.


2 Answers

This is a very standard code, just you need a small loop:

$i = 1; $baseSlug = $slug;
while(slug_exist($slug)){
    $slug = $baseSlug . "-" . $i++;        
}

return $slug;
like image 169
mcuadros Avatar answered Sep 19 '22 14:09

mcuadros


<?php
$oSlug    = 'Test';
$slug     = $oSlug;
$count = 1;
while(slug_exist($slug)){
    $slug = $oSlug.'-'.$count++;
}
print 'The slug i got is: '.$slug;
?>
like image 38
0xAli Avatar answered Sep 20 '22 14:09

0xAli