Displaying Post Date with next_post() or previous_post()? (6 posts)

  1. travelvice
    Posted 5 years ago #

    The objective is to display the dates (if applicable) of the previous and next post, instead of using the post's title or something more ambiguous.

    « March 29 | March 31 »

    I've had a look into the codex and see that next_post() & previous_post() aren't setup to do as much.

    Suggestions on the best way to go about doing this?


  2. Michael
    Forum Moderator
    Posted 5 years ago #


    something like this:

    <?php previous_post_link('&laquo; %link', get_the_time('F j, Y',get_previous_post()->ID) ) ; ?> | <?php next_post_link('%link &raquo;', get_the_time('F j, Y',get_next_post()->ID) ) ; ?>

  3. travelvice
    Posted 5 years ago #

    This is pretty neat, but looks a little expensive to run (I'm going to have it at the top and bottom of each blog page).

    I came across an interesting article on get_adjacent_post here.

    Written out the long way for future searchers to understand, what about something like...

    $in_same_cat = false;
    $excluded_categories = '';
    $previous = true;
    $previous-post = get_adjacent_post($in_same_cat, $excluded_categories, $previous);

    And then pulling the necessary info out of the returned array (simplified example):
    echo $previous-post->post_date;

  4. Michael
    Forum Moderator
    Posted 5 years ago #

    this is another possible way; then you need to convert the raw output of $post_date; and get the permalink to wrap around it for the link ...
    probably not much saved.

    it would be interesting if you could run a few quantitative comparisons and report on the resources used by each method ;-)

  5. travelvice
    Posted 5 years ago #


    Yeah, you'd still have to use build a lot of it out: ...the link (get_permalink($previous-post->ID)), convert the date, a sanitized post title for the anchor tag (if desired).

    I do like how I can keep all this in a variable though, for use again on the same page without querying all over again.

    Thanks for your thoughts!

  6. Michael
    Forum Moderator
    Posted 5 years ago #

    no problem to break the code into lines with variables; for 'prev' only:

    $previous_post_id = get_previous_post()->ID;
    $previous_time = get_the_time($previous_post_is);
    $in_same_cat = false;
    $excluded_categories = '';
    previous_post_link('&laquo; %link', $previous_time, $in_same_cat, $excluded_categories );

    probably not much difference in resources, certainly easier to understand, easier to comment for educational reasons, and better to edit in the future.

Topic Closed

This topic has been closed to new replies.

About this Topic


No tags yet.