John Davidson

php - Get Prev/Next post link via post ID in WordPress

0 comments
Message:


I am currently using the WordPress previous_post_link and next_post_link, which work as expected. The issue is that I have imported tons of posts via CSV file, so now most posts have the same date/timestamp, and WP doesn't pick the right prev/next post as it is based on date by default I believe.
I have searched other answers which show how to search the ID, but I can't seem to implement it into a link, it only returns a plain ID. For sure I'm getting it wrong as I do not have much PHP knowledge.


I am using this code:


<div class="prev"><?php previous_post_link( '%link', '%title', TRUE ); ?>&nbsp;</div>
<div class="next"><?php next_post_link( '%link', '%title', TRUE ); ?>&nbsp;</div>

I have found the code below but I don't know how to turn it into the code format above.


<?php
function get_previous_post_id( $post_id ) {
global $post;
$oldGlobal = $post;
$post = get_post( $post_id );
$previous_post = get_previous_post();
$post = $oldGlobal;
if ( '' == $previous_post )
return 0;
return $previous_post->ID;
}

echo get_previous_post_id( $current_id );

An answer that can provide a working code is much appreciated. Thanks



My Answer:
You can modify your code to use the function `get_previous_post_id` to get the previous post ID and then use that ID to generate the link. Here's how you can do it:

php





Make sure to add the `get_next_post_id` function as well:

php
function get_next_post_id( $post_id ) {
global $post;
$oldGlobal = $post;
$post = get_post( $post_id );
$next_post = get_next_post();
$post = $oldGlobal;
if ( '' == $next_post )
return 0;
return $next_post->ID;
}


This code will get the previous and next post IDs based on the current post ID and then generate the links for them.

Rate this post

3 of 5 based on 1889 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us