Support

Account

Home Forums General Issues Get field from an adjacent post

Helping

Get field from an adjacent post

  • I’m viewing the single.php page for a custom post type. At the bottom of the page I’d like to show next and previous post links that show an accompanying image. This image value is an ACF custom field. How do I get and display the next/previous posts image with links?

    Currently my broken code below shows the image of the page I’m already viewing:

    <?php 
    		
    	$size = "medium";
    	
    	$prevPost = get_previous_post(true); 
    		
    	$prevThumbnail = get_field('bg_image', $prevPost->ID); 
    	$bgimage = wp_get_attachment_image_src( $prevThumbnail, $size );
     
    ?>
    	
    	<img src="<?php echo $bgimage[0]; ?>" />
    	<?php previous_post_link( '<strong>%link</strong>' ); ?>
  • To do this you would need to use the WP get_adjacent_post() function then use the ID of that post to get the field you want from the other post get_field('field_name', $adjacent_post->ID);

Viewing 2 posts - 1 through 2 (of 2 total)

You must be logged in to reply to this topic.