I had to expand a site to handle SEO-friendly URL-s. The site was not based on a CMS, but had lot of posts in the database, so I had to do something what isn’t change the actual structure, because the site had lot of references from other sites.
I solved the problem with two easy steps.
First step
Add SEO friendly URL-s to the posts.
First, I added a new field to the database table what containd the posts, named POST_SEO varchar(1000).
Then I added the following code after the script what saved the post data into the database. (Oh yes, I needed the hungarian characters too in the SEO title, thats why they are in the preg_replace pattern. The variable $pid contained the post_id of the edited or inserted post. The $pseo variable contained the string what the user typed into the SEO-Title field. If this field was empty I created the SEO-Title from the Post-Title. Then I checked the database. If there I founded a pot , what has the same SEO-Title, I just added the post_id to the end of the title, and finally updated the record in the database.
if ($pseo==”")
$pseo= preg_replace(“/[^A-Za-z0-9áÁéÉóÓőŐöÖüÜúÚűŰíÍ_]/”,”",str_replace(” “,”_”,$post_title));
else
$pseo= preg_replace(“/[^A-Za-z0-9áÁéÉóÓőŐöÖüÜúÚűŰíÍ_]/”,”",str_replace(” “,”_”,$pseo));
$sql=”select * from post where post_seo=’$pseo’ and post_id<>$pid”;
$psr=mysql_query($sql);
if (mysql_numrows($psr)>0)$pseo.=”_”.$pid;
$sql=”update post set post_seo=’”.addslashes($pseo).”‘ where post_id=$pid”;
mysql_query($sql);
One and half step
When I want to show links to the post with the new SEO-Title, just needed to build the anchor in the following format;
<a href=”http://www.oursite.com?$post_seo“>$post_title</a>
Yes, the variable $post_seo containes the SEO-Title, and the $post_title contains the title of the post.
Second step
Find the appropriate post based on the URL.
When the users hit the link what redirects them to our site, the index.php runs first in case of the new SEO-Title URL-s.
On the top of the index.php, we have to add the following code. The database connection must be there before this code part. In this case, the SEO-Title was the only one URL parameter, so we tried to process SEO-Titles only when we had one parameter.
if (count($_GET)==1 )
{unset($post_id);
reset($_GET);
while (list($key,$value) = each($_GET))
{$sql=”select post_id from post where post_seo=”$key”;
$result=@mysql_query($sql);
if (@mysql_numrows($result)!=0)
{$post_id=mysql_result($reasult,0,0);
include “showpost.php”;
include “footer.php”
exit;
}
}
}
If we found the post based on the URL parameter’s name, we call the include what show the post content, then we show the footer and close the page, otherwise let the index.php finish the rest.



















