Saturday, July 28, 2012

Creating SEO friendly URLs with the merger of Wordpress and CodeIgniter

  1. Suppose you are required to create SEO friendly URLs with the merger of WP and CI, WP as front-end and CI as admin panel.
  2. You are adding projects with CI and showing detail of that project with WP.

  • Code in controller (project.php)
// create user friendly url string as per project name
$pro_name = “new project name”;
$pro_url = strtolower(str_replace(' ','-',trim($pro_name)));

// insert in to wp_posts table
$post = array(
'post_title' => $pro_name,
'post_name' => $pro_url,
'post_type' => 'page'
$post_id = $this->utility_model->set('wp_posts', $post);

// insert in to wp_postmeta table
$postmeta = array(
'post_id' => $post_id,
'meta_key' => '_wp_page_template',
'meta_value' => 'project-detail.php'
$this->utility_model->set('wp_postmeta', $postmeta);

/* insert in to projects table provided that pro_url must be unique. Here I insert post_id because while updating the project we also need to update wp_posts*/
$project = array(
'pro_name' => $pro_name,
'pro_url' => $pro_url,
'wp_post_id' => $post_id
$this->utility_model->set('projects', $project);
  • Code in model (utility_model.php)
 * @name: set
 * @description: add new record and return id of inserted record
 * @return: int
public function set($table, $values)
$this->db->insert($table, $values);
return $this->db->insert_id();
  • Set WP Permalink
Navigate to Settings → Permalink Settings select Post name option and save.
  • WP page template code
Create a page template [here I named project-detail.php] in your WP theme folder and add following code to fetch project detail w.r.t. pro_url.
 * Template Name: Project Detail
$pathInfo = pathinfo($_SERVER['REQUEST_URI']);
$pro_url = $pathInfo['filename'];
// fetch project info by pro_url
$query = "SELECT * FROM projects WHERE pro_url = '$pro_url' ";
$result = $wpdb->get_results($query);
  • Test url
Start apache services, in browser url bar type http://localhost/your_site/new-project-name
and that's it.

No comments:

Post a Comment