WordPress: Next / Prev Post based on post type and meta key

WordPress: Next / Prev Post based on post type and meta key

Filed under News Blog, Tutorials

Written By : Kyle Bahr

function custom_post_nav($post_type = '', $meta_key = '', $meta_value = '') {

    $pages = array();
    $args = array(
        'post_type' => $post_type,
        'meta_key' => $meta_key,
        'orderby' => 'date',
        'order' => 'DESC',
        'posts_per_page' => -1,
        'meta_value' => $meta_value
     );
    $nav_posts = get_posts($args);

    foreach($nav_posts as $nav_post) {
        $pages[] += $nav_post->ID;
    }

    $id = get_the_id();

    $current = array_search($id, $pages);
    $prevID = $pages[$current-1];
    $nextID = $pages[$current+1];

    $total = count($pages);
    foreach ($pages as $mykey => $myval) {
        if ($myval== $id) {
            $key = ($mykey + 1);
            }
    }

    $output .= '<ul class="post-nav">';

    if (!empty($prevID)) {
        $output .= '<li class="previous"><a href="'.get_permalink($prevID).'" title="'.get_the_title($prevID).'">Previous</a></li>';
    } else {
        $output .= '<li class="previous"><a href="'.get_permalink(end($pages)).'" title="'.get_the_title(end($pages)).'">Previous</a></li>';
    }
	
    $output .= '<li class="count">'.$key.' / '.$total.'</li>';
	
    if (!empty($nextID)) {
        $output .= '<li class="next"><a href="'.get_permalink($nextID).'" title="'.get_the_title($nextID).'">Next</a></li>';
    } else {
        $output .= '<li class="next"><a href="'.get_permalink(array_shift($pages)).'" title="'.get_the_title(array_shift($pages)).'">Next</a></li>';
    }
 

    $output .= '</ul>';

    return $output;

}

Written By : Kyle Bahr

With nearly ten years experience in digital media, graphic design, front-end development and creative direction, Kyle Bahr has spent the last several years growing an online presence and portfolio with EnlightenMental Productions with the hope to build continued success online and in life. A strong...

has written 9 articles