3

Im trying to make my next and previous post buttons display my custom field but for some reason it doesnt display the custom field its just blank. Heres my code.

<div id="next-prev-links">
      <?php

      $previous_post = previous_post_link('%link', ''.$image_prev.'', TRUE);
      $next_post = next_post_link('%link',''.$image_next.'', TRUE);
      $image_prev = get_post_meta( $previous_post->ID, 'image', true);
      $image_next = get_post_meta( $next_post->ID, 'image', true);
      ?>

      <?php if ( $image_prev != '' ) : ?>
        <img src="<?php echo $image_prev; ?>" alt="" />
      <?php endif; ?>

      <?php if ( $image_next != '' ) : ?>
        <img src="<?php echo $image_next; ?>" alt="" />
      <?php endif; ?>

      <?php previous_post_link('%link', 'Previous post', TRUE); ?>
      <?php next_post_link('%link', 'Next post', TRUE); ?>
</div>
2

Here's the code for what you're trying to do (accessing post custom value):

<?php    
global $post;

    $prev_post = get_adjacent_post();
    $next_post = get_adjacent_post( false, '', false );
    $prev_post_id = $prev_post->ID;
    $next_post_id = $next_post->ID;
    // this should, according to your code above, be the http://example.com/your/img.jpg string
    $prev_img_path = get_post_custom_values( 'your_key_name', $prev_post_id );
    $next_img_path = get_post_custom_values( 'your_key_name', $next_post_id );
    $prev_def_path = get_bloginfo('stylesheet_directory').'/default_next_img_inside_theme_folder.jpg';
    $next_def_path = get_bloginfo('stylesheet_directory').'/default_prev_img_inside_theme_folder.jpg';

    echo '<img src="'.!empty($prev_img_path) ? $prev_img_path : $prev_def_path.'" alt="Permalink to previous post" />';
    echo '<img src="'.!empty($next_def_path) ? $next_def_path : $next_img_path.'" alt="Permalink to next post" />';
?>
| improve this answer | |
0

I think you are trying to retrieve ID from link string that *_post_link() functions return, rather than post object.

If you need full object of next/previous post you should use get_adjacent_post().

PS it is good practice to develop with WP_DEBUG enabled, it makes much easier to catch type mismatches.

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.