Skip to content

Instantly share code, notes, and snippets.

@stirtingale
Last active March 2, 2020 10:55
Show Gist options
  • Save stirtingale/cf5aa5716f23730c308d8e8f16dcc0c8 to your computer and use it in GitHub Desktop.
Save stirtingale/cf5aa5716f23730c308d8e8f16dcc0c8 to your computer and use it in GitHub Desktop.
Get next post in current URL category Wordpress
<?php
// BASED ON @ https://wordpress.stackexchange.com/questions/149826/display-posts-from-the-same-category-using-next-previous-post-link
$post_id = $post->ID; // current post ID
$cat = get_the_category();
$current_cat_id = $cat[0]->cat_ID; // current category ID
$cat_id = get_queried_object_id();
// GET CAT FROM URL
// this is hacky as hell.
$current_url = home_url( add_query_arg( array(), $wp->request ) );
$u = parse_url($current_url);
$r = array_reverse(explode('/', $u['path'])); // note flipping because base might change. e.g. currently second from first is 2020. That will change. So flip will give you penulimate.
$l = $r[1];
$cat_slug = $l;
$args = array(
'post_type' => 'portfolio',
'tax_query' => array(
array(
'taxonomy' => 'category',
'field' => 'slug',
'terms' => $cat_slug
)
),
'posts_per_page' => 999,
'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 );
$goto_previous = isset( $ids[ $thisindex - 1 ] ) ? $ids[ $thisindex - 1 ] : 0;
$goto_next = isset( $ids[ $thisindex + 1 ] ) ? $ids[ $thisindex + 1 ] : 0;
if ( $goto_previous ):
$root = get_post_type_archive_link( 'portfolio' );
$post_slug = get_post_field( 'post_name', $goto_previous );;
// $link = get_permalink();
$link = $root . $cat_slug ."/". $post_slug;
?>
<div class="l-prev ">
<a rel="prev" href="<?php echo $link ?>"><?php echo get_the_title($goto_previous); ?></a>
</div>
<?php
endif; // prev
if ( $goto_next ):
$root = get_post_type_archive_link( 'portfolio' );
$post_slug = get_post_field( 'post_name', $goto_next );;
// $link = get_permalink();
$link = $root . $cat_slug ."/". $post_slug;
?>
<div class="l-next ">
<a rel="next" href="<?php echo $link ?>"><?php echo get_the_title($goto_next); ?></a>
</div>
<?php
endif; //next
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment