I am working on a portfolio website. Whenever a portfolio piece is clicked, the user is taken to a page that shows details about that piece (i.e. more photos and information). There will also be previous and next navigation links to get to additional pieces. However, I want the previous and next navigation links to be a thumbnail photo of the next piece (custom field for that is thumbnail_photo). This is what I have so far:

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

       <p><?php echo $prev_value; ?></p>
       <p><?php echo $next_value; ?></p>

I used 'materials' in the call for $prev_value since 'materials' is another custom field. I just wanted to see if it was actually working. It outputs the materials just fine, but it only outputs the ID number of the thumbnail_photo. I can't get it to reference the file name so that I can output the actual image.

I am using the Advanced Custom Fields plugin, so each image is stored as an image object. So this is how I would typically output a thumbnail image:

<?php
  $image = get_field('thumbnail_photo);
  echo $image[sizes]["thumbnail"];  // thumbnail is a reference to wordpress' thumbnail media size
?>
有帮助吗?

解决方案

When you configure the ACF input field, be sure you set the return value to be an image object instead of the image ID after change this, or if you already changed, you have to update the post or posts you're trying to get. Because, if you set the field return value as image ID, created the posts and now you wanna change their values you have to modify all the posts because every post_meta is containing the ID of the image.

In the ACF website has a tutorial how you could get the values an turn into images:

With the ID

<?php
    wp_get_attachment_image( $next_value, 'thumbnail' );
?>

Another Example With the ID, but this time you have to create the image HTML, the function returns an array with the url, width and height

<?php

$image = wp_get_attachment_image_src( $next_value, 'thumbnail' );
// url = $image[0];
// width = $image[1];
// height = $image[2];
?>
<img src="<?php echo $image[0]; ?>" />

You could do a check for the returned value and then write the image, example:

<?php
if( is_int( $next_value ) ) {
    wp_get_attachment_image( $next_value, 'thumbnail');
} elseif ( is_object( $next_value ) ) {
    echo $next_value['sizes']['thumbnail'];
} else { ?>
   <img src="<?php the_field('field_name'); ?>" alt="" />
<?php } ?>

I didn't test it, but I think it works fine.

I hope this help and sorry for the bad english

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top