Post Navigation for Use with Types & Views and URL Parameters

This code is an example of post navigation for use specifically with Types & Views. The post navigation works well in tandem with View’s parametric search forms, and can output next/previous post links based on URL parameters that indicate custom taxonomies and fields.

You can see this code in action at: http://dev.rocketdogrescue.org/adopt/adoptees/. Enter some search criteria and then click on an individual dog to check out the post navigation.

$post_type, 'adoption-status' => $url_params[ 'status' ], 'dog-breed' => $url_params[ 'breed' ], ); /* Add custom field args for CPT 'dog' since these don't work for success stories */ if ( 'dog' == $post_type ) { // Only add non-empty custom fields and the specific custom fields we want foreach ( $url_params as $k => $v ) { if ( strstr($k, "wpcf") && !empty( $v ) ) { $args[ 'meta_query' ][] = array ( 'key' => $k, 'value' => $v ); } } } $query = new WP_Query( $args ); $i = 0; while ($query->have_posts()) { $query->the_post(); $id = get_the_ID(); // If we're on the current post if ( $id == $current_ID ) { $next_post = $query->posts[ $i-1 ]; $prev_post = $query->posts[ $i+1 ]; } $i++; } wp_reset_postdata(); // Output next post if ( !empty( $next_post ) ) { echo ''; } // Don't output adoption status parameter, but do save it for selecting the appropriate $links[] below $status = $url_params[ 'status' ]; $status = !empty($status) ? '-' . $status : ''; $url_params[ 'status' ] = ''; // Get URL parameters and remove empty array items - done automatically with call to array_filter with no callback function $params = implode( ', ', array_filter( $url_params ) ); // Remove hyphens and capitalize $params = ucwords( str_replace( '-', ' ', $params ) ); // Top level links $links[ 'dog' ] = '/adopt/adoptees/'; $links[ 'dog-for-adoption' ] = '/adopt/adoptees/'; $links[ 'dog-needs-foster-home' ] = '/dogs-for-adoption-in-san-francisco-bay-area-rocket-dog-rescue-san-francisco/'; $links[ 'success-story' ] = '/adopt/success-stories/'; // Output middle post type link echo ''; echo get_post_type_object( $post_type )->labels->name; echo !empty( $params ) ? ': ' . $params : ''; echo ''; // Output pevious post if ( !empty( $prev_post ) ) { echo ''; } ?>

Leave a Comment

Your email address will not be published. Required fields are marked *

%d bloggers like this: