Struggling to generate a unique slug

  • I'm trying to create a unique slug for news articles.


    I've seen reference in other forum posts about being able to combine multiple ids, however I cannot get it to work.


    Code
    1. <perch:content id="_id" suppress="true" />
    2. <perch:content id="title" type="Text" label="Title" title suppress />
    3. <perch:content id="slug" type="slug" for="title _id" suppress="true" />

    This only ever generates the slug using the title, it does not append the _ID on the first save, only the second save once the id field has been populated.


    Is there an easier way to get a unique slug as some of the articles will most likely share a title.

  • Hi Tony,


    The slug you generate does not need to include the item's unique ID in order for you to use it in the item's URL and when fetching the item from the database. The item's URL in your template can be something like this:


    HTML
    1. <a href="/post.php?s=<perch:content id="slug">-<perch:content id="_id">">
    2. <perch:content id=title">
    3. </a>



    In your PHP page, you can get the value of ?s= (i.e. the item's slug in this case) with perch_get('s') and separate the last segment of the slug:



    I'd personally use the _id option (because Perch uses a faster a database query with it), and check the slug from the URL matches the slug I get from the database in PHP:


    PHP
    1. $item = perch_collection('Blog', [
    2. '_id' => $ID,
    3. 'skip-template' => true,
    4. 'return-html' => true,
    5. ]);