I have this shortcode (I wrote it in functions.php) that shows the read previous and read next links in a single post:
<?php
function prev_next_buttons_post() {
$html = '';
$html .= '<div class="container-single-post-buttons">';
$html .= '<div class="prev-next-buttons">' . previous_post_link('%link', '< read previous') . '</div>';
$html .= '<a href="/blog" class="btn-btd-black">back to blog</a>';
$html .= '<div class="prev-next-buttons">' . next_post_link('%link', 'read next >') . '</div>';
$html .= '</div>';
return $html;
}
add_shortcode('prev_next_buttons', 'prev_next_buttons_post');
The problem I have is that when I add the shortcode:
<section>
<div class="container btd-container-sm">
<?php echo do_shortcode('[prev_next_buttons]') ?>
</div>
</section>
when inspecting it shows the different structure and the links are outside their containers losing their styles:
I need them to be in the same structure as defined in my shortcode. How could I solve this? Please help.
Advertisement
Answer
This is because previous_post_link
and next_post_link
do not return a value, but write to the output buffer directly.
You need to use their counterparts that return the value, so that you can then concatenate those into your string – get_previous_post_link
and get_next_post_link
.
(If you check the source code for the former two functions, you’ll see that they are just wrapper functions that call the latter two, and echo
their return values – https://developer.wordpress.org/reference/functions/previous_post_link/#source)