X

How to Display Custom Field Value of Previous and Next Post

Snippets by IsItWP

Are you looking for a way to display the custom field value from previous and next posts? While there’s probably a plugin for this, we have created a quick code snippet that you can use to display custom field value of previous and next post.

Instructions:

All you have to do is add this code to your theme’s functions.php file or in a site-specific plugin:

<?php
  $previous_post = get_previous_post();
  $next_post = get_next_post();
  $prev_value = get_post_meta( $previous_post->ID, 'CUSTOM_FIELD', $single = true);
  $next_value = get_post_meta( $next_post->ID, 'CUSTOM_FIELD', $single = true);
?>


<?php if ( $prev_value != '' ) : ?>
       <p><?php echo $prev_value; ?></p>
       <p><?php echo $next_value; ?></p>
<?php endif; ?>

Make sure to change the CUSTOM_FIELD on line 4 and 5 to the name of the custom field you wish to display.

Note: If this is your first time adding code snippets in WordPress, then please refer to our guide on how to properly add code snippets in WordPress, so you don’t accidentally break your site.

If you liked this code snippet, please consider checking out our other articles on the site like: 27 best WordPress themes for affiliate marketing and how to use Google Optimize in WordPress.

Comments   Leave a Reply

  1. Fantastic! Thank you. Exactly what I needed.

  2. Thank You for your snippet, If refreshed the page 5times views counts getting increase, so how to remove / no increment / duplicate view count in this snippet

  3. Top 100+ websites about WordPress (part 1) June 17, 2016 at 5:18 pm

    […] How to display custom fields value of previous and next post […]

  4. Nice snippet

  5. Thank you! Works perfectly!

  6. That is what I needed! I added DVD covers as custom fields and I want to call them for navigation. that does the trick, thanks!

    1. Ahhh very cool use of this snippet sounds great. Glad to hear you like the snippet.

    2. Ahhh very cool use of this snippet sounds great. Glad to hear you like the snippet.

  7. yeaaaaah,
    thanks for this code, i allways ask about this code, but finnaly found it her 🙂
    i can now creat my photo portfolio and to show the next or prev photo.
    Thanks a lot SIR.

    1. Cool glad I could help,

Add a Comment

We're glad you have chosen to leave a comment. Please keep in mind that all comments are moderated according to our privacy policy, and all links are nofollow. Do NOT use keywords in the name field. Let's have a personal and meaningful conversation.

WordPress Launch Checklist

The Ultimate WordPress Launch Checklist

We've compiled all the essential checklist items for your next WordPress website launch into one handy ebook.
Yes, Send Me the Free eBook!