
Sometimes you may want to show the previous and next post title from same category just below your post. Here I am sharing you the code which i got from internet and used for someone which worked great. Here I am sharing you the corresponding css and php code.
CSS Code ( This code may need to tweak based on your theme)
div#opagination a[rel="prev"] {
float: left;
width: 50%;
}
div#opagination span {
margin-left: 12px;
margin-right: 12px;
}
div#opagination center {
display: inline;
}
span.nextpost.txt {
float: right;
}
span.prevpost.txt {
float: left;
}
div#opagination a[rel="next"] {
float: right;
width: 50%;
display:block;
}
div#opagination * {
font-size: 15px;
}
div#opagination a span:last-child,div#opagination a span:last-child * {
/* background: red; */
display: block;
font-size: 23px;
font-weight: bold;
text-align:center;
clear: both;
}
div#opagination a span:first-child,div#opagination a span:first-child * {
font-weight: bold;
color: #ab9797 !important;
}
PHP code (That will go in your single.php file)
<?php
$post_id = $post->ID; // current post ID
$cat = get_the_category();
$current_cat_id = $cat[0]->cat_ID; // current category ID
$args = array(
'numberposts'=>-1,
'category' => $current_cat_id,
'orderby' => 'post_date',
'order' => 'DESC'
);
$posts = get_posts( $args );
// get IDs of posts retrieved from get_posts
$ids = array();
foreach ( $posts as $thepost ) {
$ids[] = $thepost->ID;
}
// get and echo previous and next post in the same category
$thisindex = array_search( $post_id, $ids );
//print_r($ids);
$previd = isset( $ids[ $thisindex - 1 ] ) ? $ids[ $thisindex - 1 ] : false;
$nextid = isset( $ids[ $thisindex + 1 ] ) ? $ids[ $thisindex + 1 ] : false;
echo '<div id="opagination">' ;
if (false !== $previd ) {
?><a rel="prev" href="<?php echo get_permalink($previd) ?>"><span class="prevpost txt"><< Article plus récent </span><span><?php echo get_the_title($previd); ?></span></a><?php
}
if (false !== $nextid ) {
?><a rel="next" href="<?php echo get_permalink($nextid) ?>"><span class="nextpost txt">Article plus ancien >></span> <span><?php echo get_the_title($nextid); ?> </span> </a><?php
}
echo '</div>';
?>