Hello,
This post as the title says talks about getting URL for next and previous post. Please note that post is not same as page.
All the required functions and hints can be found in link-template.php file under wp-includes
Let me show you how you can get permalinks for next and previous post without doing anything fancy.
Get Previous post URL
First of all we will get hold of post object for the previous post as shown below
We will use adjacent_post_link() function. Definition of this function is given below
1 2 3 4 5 6 7 8 9 10 11 12 13 |
/** * Retrieve adjacent post. * * Can either be next or previous post. * * @since 2.5.0 * * @param bool $in_same_cat Optional. Whether post should be in a same category. * @param array|string $excluded_categories Optional. Array or comma-separated list of excluded category IDs. * @param bool $previous Optional. Whether to retrieve previous post. * @return mixed Post object if successful. Null if global $post is not set. Empty string if no corresponding post exists. */ function get_adjacent_post($in_same_cat = false, $excluded_categories = '', $previous = true) {} |
So to get the previous post link do this
1 2 3 4 5 6 7 |
$post = get_adjacent_post(); // check if $post is valid object if($is_object($post)) { $previous_post_permalink = get_permalink($post->ID); echo $previous_post_permalink; } // $previous_post_permalink will have value similar to http://local.wordpress/?p=1 |
Above usage of function get_adjacent_post pass on default values for all the params function accepts. You can pass on custom values for it to behave differently.
Now lets check how we can get next post permalink
Get Next post URL
Pretty much the same functionality but with one core difference. $previous should be set to false as shown below
1 2 3 4 5 6 7 |
$next_post = get_adjacent_post(false,'',false); // check if $next_post is valid object. It will be null if there isn't any next post if($is_object($next_post)) { $next_post_permalink = get_permalink($next_post->ID); echo $next_post_permalink; } // $next_post_permalink will have value similar to http://local.wordpress/?p=3 |
As you can see that its pretty straight forward.
I hope this helps. Please let me know if you have something to add of the above code can be improved. Don’t forget to leave you comments. Once again I would like to add that getting post link is not same as getting page link.
Here is a useful read from wordpress codex
http://codex.wordpress.org/Next_and_Previous_Links
The above post explains how to get page URLs.
If you have any questions please let me know so that either myself or any other reader reading this post can answer your question.s
Cheers
Leave a Reply