Skip to content

Instantly share code, notes, and snippets.

@dannydickson
Last active December 11, 2022 20:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dannydickson/b375e44bc409f0595e6ab32d2c61fdff to your computer and use it in GitHub Desktop.
Save dannydickson/b375e44bc409f0595e6ab32d2c61fdff to your computer and use it in GitHub Desktop.
WordPress custom post navigation inside of a shortcode
<?php
function custom_post_navigation_function() {
ob_start();
// Setup and store previous post variables
$prev_post = get_previous_post();
$prev_id = $prev_post->ID;
$prev_title = $prev_post->post_title;
$prev_link = get_permalink( $prev_id );
$prev_thumb = get_the_post_thumbnail( $prev_post->ID, 'thumb', array('class' => 'previous-post-image'));
// Stores previous post markup in variable to be called later in the function
$custom_previous_postnav = '<a href="' . $prev_link . '" class="custom-previous-post_wrap">';
$custom_previous_postnav .= '<div class="custom-previous-post_image-wrap">' . $prev_thumb . '</div>';
$custom_previous_postnav .= '<div class="custom-previous-post_content">';
$custom_previous_postnav .= '<div class="previous-post-sub-title">« Previous</div>';
$custom_previous_postnav .= '<div class="previous-post-title">' . $prev_title . '</div>';
$custom_previous_postnav .= '<div class="custom-previous-post_content_read-more-link">Read more <span class="right-arrow">→</span></div>';
$custom_previous_postnav .= '</div></a>';
// Setup and store next post variables
$next_post = get_next_post();
$next_id = $next_post->ID;
$next_title = $next_post->post_title;
$next_link = get_permalink( $next_id );
$next_thumb = get_the_post_thumbnail( $next_post->ID, 'thumb', array('class' => 'next-post-image'));
// Stores next post markup in variable to be called later in the function
$custom_next_postnav = '<a href="' . $next_link . '" class="custom-next-post_wrap">';
$custom_next_postnav .= '<div class="custom-next-post_content">';
$custom_next_postnav .= '<div class="next-post-sub-title">Next »</div>';
$custom_next_postnav .= '<div class="next-post-title">' . $next_title . '</div>';
$custom_next_postnav .= '<div class="custom-next-post_content_read-more-link">Read more <span class="right-arrow">→</span></div>';
$custom_next_postnav .= '</div>';
$custom_next_postnav .= '<div class="custom-next-post_image-wrap">' . $next_thumb . '</div>';
$custom_next_postnav .= '</a>';
// Wrap both prev and next nav in a container and output markup for both
$custom_postnav = '<div class="custom-post-nav d-flex justify-content-between">' . $custom_previous_postnav . $custom_next_postnav . '</div>';
// Outputs all markup
return $custom_postnav;
ob_get_clean();
}
add_shortcode('custom_post_navigation', 'custom_post_navigation_function');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment