I am working on a basic blog application in Codeigniter 3.1.8.
The posts are diaplayed on the homepage and also filtered by categories.
Whenever I try to view a post from a category page its url has the category id at the end, instead of the post id. All post in the category with id 1 link to http://localhost/ciblog/posts/post/1
.
In the Posts_model model there is:
public function get_posts_by_category($id, $limit, $offset) {
$this->db->order_by('posts.id', 'DESC');
$this->db->limit($limit, $offset);
$this->db->join('categories', 'categories.id = posts.cat_id');
$query = $this->db->get_where('posts', array('cat_id' => $id));
return $query->result();
}
In the Categories controller:
public function posts($id) {
$this->load->library('pagination');
$config = [
'base_url' => base_url('/categories/posts/' . $id),
'page_query_string' => TRUE,
'query_string_segment' => 'page',
'display_pages' => TRUE,
'use_page_numbers' => TRUE,
'per_page' => 12,
'total_rows' => $this->Posts_model->get_num_rows_by_category($id),
//More code
];
if (!isset($_GET[$config['query_string_segment']]) || $_GET[$config['query_string_segment']] < 1) {
$_GET[$config['query_string_segment']] = 1;
}
$limit = $config['per_page'];
$offset = ($this->input->get($config['query_string_segment']) - 1) * $limit;
$this->pagination->initialize($config);
$data = $this->Static_model->get_static_data();
$data['categories'] = $this->Categories_model->get_categories();
$data['category_name'] = $this->Categories_model->get_category($id)->name;
$data['posts'] = $this->Posts_model->get_posts_by_category($id, $limit, $offset);
$this->load->view('partials/header', $data);
$this->load->view('categories/posts');
$this->load->view('partials/footer');
}
The posts view in the above controller:
<div class="container">
<div class="col-xs-12">
<h1 class="display-4 category-name"><?php echo $category_name; ?></h1>
</div>
<?php if ($posts): ?>
<div class="posts-grid">
<?php foreach ($posts as $post) :?>
<div class="col-xs-12 col-sm-6 col-lg-4 col-xl-3">
<div class="post">
<div class="thumbnail">
<a href="<?php echo base_url('posts/post/') . $post->id; ?>">
<img src="<?php echo base_url('assets/img/posts/') . $post->post_image; ?>" />
</a>
</div>
<div class="text">
<h2 class="card-title">
<a href="<?php echo base_url('posts/post/') . $post->id; ?>">
<?php echo $post->title; ?>
</a>
</h2>
<p class="text-muted"><?php echo $post->description; ?></p>
</div>
<div class="read-more">
<a class="btn btn-block btn-sm btn-success" href="<?php echo base_url('posts/post/') . $post->id; ?>">Read more</a>
</div>
</div>
</div>
<?php endforeach ?>
</div>
<?php else: ?>
<div class="col-xs-12">
<p class="text-muted" id="no_posts">There are no posts in the <?php echo $category_name; ?> category yet.</p>
</div>
<?php endif; ?>
<?php $this->load->view("partials/pagination");?>
</div>
The posts images, titles, etc are displayed correctly. Not the links to the single post...
Where is my mistake?