• Hi there,

    I need to retrieve the ID and/or slug of the next or previous post. I was testing some stuff out with the following code:

    <?php $prev_post = get_adjacent_post( true, '', true, 'taxonomy_slug' ); ?>
    			<?php if ( is_a( $prev_post, 'WP_Post' ) ) { ?>
    			   <a href="<?php echo get_permalink( $prev_post->ID ); ?>"><?php echo get_the_title( $prev_post->ID ); ?></a>
    			<?php } ?>

    I found this here: https://codex.www.ads-software.com/Function_Reference/get_next_post

    It has to be working in the single.php file, here’s an example:

    <?php
    /**
     * @package WordPress
     * @subpackage HTML5-Reset-WordPress-Theme
     * @since HTML5 Reset 2.0
     */
     get_header(); ?>
    
    	<?php if (have_posts()) : while (have_posts()) : the_post(); ?>
    
    		<article <?php $post_class() ?> id="post-<?php the_ID(); ?>">
    			
    			<h1 class="entry-title"><?php the_title(); ?></h1>
    
    			<div class="entry-content">
    				
    				<?php the_content(); ?>
    
    				<?php wp_link_pages(array('before' => __('Pages: ','html5reset'), 'next_or_number' => 'number')); ?>
    				
    				<?php the_tags( __('Tags: ','html5reset'), ', ', ''); ?>
    			
    				<?php posted_on(); ?>
    				
    				
    				
    			</div>
    			
    			<?php $prev_post = get_adjacent_post( true, '', true, 'taxonomy_slug' ); ?>
    			<?php if ( is_a( $prev_post, 'WP_Post' ) ) { ?>
    			   <a href="<?php echo get_permalink( $prev_post->ID ); ?>"><?php echo get_the_title( $prev_post->ID ); ?></a>
    			<?php } ?>
     
    		</article>
    
    	<?php comments_template(); ?>
    
    	<?php endwhile; endif; ?>
    
    <?php post_navigation(); ?>
    
    <?php get_footer(); ?>

    BUT, this code does not seem to work. Can anyone show me how this code works, or another way to get the post ID and/or slug?

    Kind regards,
    Namteor

    • This topic was modified 7 years, 11 months ago by namteor.
Viewing 1 replies (of 1 total)
  • Moderator bcworkz

    (@bcworkz)

    This function needs to be inside the loop to work properly. If you need it to work outside of the loop, assign the current post’s object to global $post before calling the function.

Viewing 1 replies (of 1 total)
  • The topic ‘Next Post / Prev Post ID or Slug’ is closed to new replies.