Make a post slug unique

左心房为你撑大大i 提交于 2019-12-04 06:07:59

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;
<?php
$oSlug    = 'Test';
$slug     = $oSlug;
$count = 1;
while(slug_exist($slug)){
    $slug = $oSlug.'-'.$count++;
}
print 'The slug i got is: '.$slug;
?>

If you have full access to your db and like store logic in db you can

  • add unique index to slug and catch exception on insert
  • add trigger on insert to do slug generation work for you

I had been working on mine for a few hours before I stumbled upon this. This question assisted me a little but I ended up with something a bit different;

I had also created a function to check if a slug already exists;

function slugExist($slug){
    global $db;
    $query = $db->query("SELECT * FROM `blog-posts` WHERE `slug` = '".$slug."'");
    $results = $query->num_rows;
    if($results > 0){
        return true;
    }else{
        return false;
    }
}

For Posting a new Article or Post (depending on what you are doing) I have the following;

    $slug = furl($_POST['title']);

    $CheckSlug = $db->query("SELECT * FROM `blog-posts` WHERE `slug` LIKE '".$slug."%'");
    $numHits = $CheckSlug->num_rows;
    if($numHits > 0){
        $slug = $slug.'-'.$numHits;
    }

This is much easier on execution as there is no loop and it's very clean. But what if you are editting an existing post? You want the slug to change if they change the title but you dont want it to change or increase/decrease the numeric suffix if the user doesn't.

So using a few posts I ended up with this;

$slug = furl($_POST['title']);

if($slug != $oldSlug){                      // 1. If the slug of the new title is different to the old one, proceed to adding suffix
    $i = 1; $baseSlug = $slug;              // 2. Set counter and baseSlug vars.
    while(slugExist($slug)){                // 3. Start a loop to keep adding to the numeric value until an empty one is found
        $slug = $baseSlug . "-" . $i++;     // 4. Set the new slug variable to the base with a new number
        if($slug == $oldSlug){              // 5. If the slug with the added number matchs the existing slug, then we dont want to change it
            break;                          // 6. Break the loop to prevent additional numeric changes to the slug
        }
    }
}

I know this is a bit of an older question but I hope that this helps at least one other person in the future.

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