如何在CodeIgniter分页中用字符串替代数字生成文章链接
嘿,这个需求挺常见的,要把CodeIgniter博客的文章链接从带ID的格式改成SEO友好的slug格式,咱们一步步来搞定它就行!
1. 先给数据库加个slug字段
首先得在你的文章表(比如叫posts)里新增一个slug字段,用来存储文章标题转成的唯一短字符串(比如把“I am an article title”转成“i-am-an-article-title”)。记得给这个字段设置唯一索引,避免出现重复的slug。
2. 生成并存储Slug
在你创建/编辑文章的控制器里,用CodeIgniter内置的url_title()函数把标题转成slug,再和文章数据一起存入数据库:
// 假设$title是用户输入的文章标题 $slug = url_title($title, '-', TRUE); // 第三个参数TRUE表示转成小写字母 // 后续把$slug和标题、内容等数据一起插入/更新到数据库
3. 配置路由(关键步骤!)
打开application/config/routes.php,添加一条路由规则,让CodeIgniter能识别slug格式的URL:
$route['blog/article/(:any)'] = 'blog/article/$1';
这条规则会把http://example.com/blog/article/xxx的请求转发到Blog控制器的article方法,同时把xxx作为参数传递过去。
4. 修改文章详情的控制器方法
原来的article方法可能是通过ID查询文章,现在改成通过slug查询:
public function article($slug) { $this->load->model('Post_model'); // 通过slug获取对应文章 $data['post'] = $this->Post_model->get_post_by_slug($slug); if (!$data['post']) { // 找不到对应slug的文章就显示404页面 show_404(); } $this->load->view('blog/article_detail', $data); }
5. 模型里新增slug查询方法
在你的文章模型(比如Post_model.php)里添加通过slug查询文章的方法:
public function get_post_by_slug($slug) { $query = $this->db->get_where('posts', array('slug' => $slug)); return $query->row(); // 返回单条文章记录 }
6. 调整分页的上下页链接逻辑
因为你是每页展示一篇文章,默认的分页类生成的是页码链接,咱们需要改成直接生成前后篇文章的slug链接:
控制器部分
public function index() { $this->load->model('Post_model'); $this->load->library('pagination'); // 获取当前页码(默认第1页) $page = $this->uri->segment(3) ? $this->uri->segment(3) : 1; $offset = ($page - 1) * 1; // 每页1篇,计算偏移量 // 获取当前页的文章 $current_post = $this->Post_model->get_post_by_offset($offset); if (!$current_post) { show_404(); } // 获取上一篇和下一篇文章的slug $data['prev_slug'] = $this->Post_model->get_previous_post($current_post->id)->slug ?? NULL; $data['next_slug'] = $this->Post_model->get_next_post($current_post->id)->slug ?? NULL; $data['current_post'] = $current_post; $this->load->view('blog/index', $data); }
模型补充方法
// 通过偏移量获取文章(用于分页定位) public function get_post_by_offset($offset) { $query = $this->db->order_by('id', 'DESC') ->limit(1, $offset) ->get('posts'); return $query->row(); } // 获取上一篇文章 public function get_previous_post($current_id) { $query = $this->db->where('id <', $current_id) ->order_by('id', 'DESC') ->limit(1) ->get('posts'); return $query->row(); } // 获取下一篇文章 public function get_next_post($current_id) { $query = $this->db->where('id >', $current_id) ->order_by('id', 'ASC') ->limit(1) ->get('posts'); return $query->row(); }
7. 在视图里渲染上下页链接
最后在博客页面的视图文件里,手动生成上一页和下一页的slug链接:
<!-- 上一页链接 --> <?php if (isset($prev_slug)): ?> <a href="<?php echo base_url('blog/article/' . $prev_slug); ?>">← 上一篇</a> <?php endif; ?> <!-- 下一页链接 --> <?php if (isset($next_slug)): ?> <a href="<?php echo base_url('blog/article/' . $next_slug); ?>">下一篇 →</a> <?php endif; ?>
这样设置完成后,你的博客文章链接就会变成http://example.com/blog/article/i-am-an-article-title这种SEO友好的格式,分页的上下页也会直接指向对应文章的slug链接啦!
内容的提问来源于stack exchange,提问作者Sylvester hillary




