How to create slug alias from Title using PHP & Joomla

Select your language

Step 1: Add createSlug and generateUniqueAlias functions

We need to add slug / alias functions inside controller.

<?php
public function createSlug($title) { // Convert to lowercase $slug = strtolower($title); // Remove HTML tags $slug = strip_tags($slug); // Replace special characters with a space $slug = preg_replace('/[^\p{L}\p{Nd}]+/u', '-', $slug); // Remove multiple dashes $slug = preg_replace('/-+/', '-', $slug); // Trim dashes from the beginning and end $slug = trim($slug, '-'); return $slug; } public function generateUniqueAlias($alias, $table, $column ) { $db = Factory::getDBO(); $uniqueAlias = $alias; $suffix = 1; // Prepare the query to check for duplicates. $query = $db->getQuery(true) ->select($db->quoteName($column)) ->from($db->quoteName($table)) ->where($db->quoteName($column) . ' like ' . $db->quote($uniqueAlias)).''; // echo $query; while ($db->setQuery($query)->loadResult()) { $uniqueAlias = $alias . '-' . $suffix; $suffix++; $query = $db->getQuery(true) ->select($db->quoteName($column)) ->from($db->quoteName($table)) ->where($db->quoteName($column) . ' = ' . $db->quote($uniqueAlias)); } return $uniqueAlias; } ?>

 

Later we will call these functions in save function using following code to get unique slug/alias:

<?php
$post['slug']=($post['slug']!="")?$post['slug']:$this->createSlug($post['txtName']); // Example usage: // Assuming $db is your database connection object in Joomla $alias = $post['slug']; $table = "#__company"; $column = "slug"; $uniqueAlias = $this->generateUniqueAlias($alias, $table, $column ); $post['slug']=$uniqueAlias;
// Output : title-1, title-2, title-3 respectively, if Title is already found,

 

Hope this helped.


Still need help! no problem, feel free to contact us Today


 Abdul Waheed : (Hire Joomla & PHP Pakistani Freelancer)