Skip to content

Instantly share code, notes, and snippets.

@raoulwegat
Created April 1, 2015 01:49
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 raoulwegat/fc8e1b7a95e97eca70e5 to your computer and use it in GitHub Desktop.
Save raoulwegat/fc8e1b7a95e97eca70e5 to your computer and use it in GitHub Desktop.
WordPress custom post type with custom ordered post navigation
<?php
/*
* I have a custom post type for my Portfolio, using Advanced Custom Fields for extra fields including a field for me to
* order the portfolio entires how I want. Standard single navigation using previous_post_link and next_post_link don't work as they
* return the order the posts were added. This fixes things:
*/
// New query
$args = array(
'post_type' => 'portfolio',
'meta_key' => 'portfolio_order',
'orderby' => 'meta_value_num',
'order' => 'ASC',
'posts_per_page' => '-1'
);
$nav_query = new WP_Query($args);
// Get an ordered list of the IDs and Title of portfolio entries
$ids = array();
while( $nav_query->have_posts() ): $nav_query->the_post();
$ids[] = array('ID' => $post->ID, 'post_title' => $post->post_title);
endwhile;
wp_reset_query();
// Reindex the list and set previous and next title & IDs
$thisindex = array_search($post->ID, array_column($ids, 'ID'));
if ($thisindex > 0) {
$prev_post_id = $ids[$thisindex-1]['ID'];
$prev_post_title = $ids[$thisindex-1]['post_title'];
}
if ($thisindex < max(array_keys($ids))) {
$next_post_id = $ids[$thisindex+1]['ID'];
$next_post_title = $ids[$thisindex+1]['post_title'];
}
?>
<div class="article-nav">
<?php if ( !empty($prev_post_id) ) { ?>
<div class="nav-left"><a href="<?php echo get_permalink($prev_post_id); ?>" rel="prev"><div class="article-prev"><span><?php echo $prev_post_title; ?></span></div></a></div>
<?php } ?>
<?php if ( !empty($next_post_id) ) { ?>
<div class="nav-right"><a href="<?php echo get_permalink($next_post_id); ?>" rel="next"><div class="article-next"><span><?php echo $next_post_title; ?></span></div></a></div>
<?php } ?>
</div>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment