get the title – get_the_title() and get_permalink() by ID of another post


I am trying to build out some custom next/previous links for a post type. The problem is that I can’t use the built-in next/prev functionality because I don’t want to include all of the posts from this post type in the next/prev links.

I have the post IDs of the next/prev posts I want to link to hardcoded, but get_the_title() and get_the_permalink() are not working as I expect.

As an example. Let’s say the current post I am viewing has the ID 9. The previous post has the ID 4 and the next post has the ID 15

I am adding the links like this:

<a href="<?php get_permalink(4); ?>">Prev: <?= get_the_title(4); ?></a>
<a href="<?php get_permalink(15); ?>">Next: <?= get_the_title(15); ?></a>

The result I am getting is strange. Both of the hrefs end up being the link to the current post I am viewing. The text of the previous link is actually the correct title I am expecting for the previous post but the title of the next link is the title of the post I am currently viewing. Do I have to reset the post data or something like that?

user19103974 2 months 2022-10-14T14:48:19-05:00 0 Answers 0 views 0

Leave an answer