|
<?php |
|
/** |
|
* If standard single navigation using previous_post_link and next_post_link don't work try this function. |
|
* By default this function uses date criteria to find next and previous post. See the default values below. |
|
* |
|
*/ |
|
function px_get_custom_post_nav( $args = array() ) |
|
{ |
|
if( ! is_single() ) { |
|
return; |
|
} |
|
|
|
$defaults = array( |
|
'post_id' => get_the_ID(), |
|
'orderby' => 'date', |
|
'post_type' => 'post', |
|
'taxonomy' => null, |
|
'in_same_term' => true, |
|
'meta_query' => array(), |
|
'output' => 'html' |
|
); |
|
|
|
$args = wp_parse_args($args, $defaults); |
|
|
|
$output = array(); |
|
$current_post_date = get_the_date('r', $args['post_id']); |
|
|
|
$query_args = array( |
|
'post_type' => $args['post_type'], |
|
'meta_query' => $args['meta_query'], |
|
'orderby' => $args['orderby'] |
|
); |
|
|
|
if( true === $args['in_same_term'] && null !== $args['taxonomy'] ) |
|
{ |
|
if( ! taxonomy_exists($args['taxonomy']) ) { |
|
return new WP_Error( 'invalid_taxonomy', __('Invalid taxonomy') ); |
|
} |
|
|
|
$terms = wp_get_post_terms($args['post_id'], $args['taxonomy'], array('fields' => 'ids')); |
|
$query_args = array_merge($query_args, array( |
|
'tax_query' => array( |
|
array( |
|
'taxonomy' => $args['taxonomy'], |
|
'fields' => 'term_id', |
|
'terms' => (int) @$terms[0] |
|
) |
|
) |
|
) |
|
); |
|
} |
|
|
|
$query_args = array_merge(apply_filters('px_get_custom_post_nav_query_args', $query_args), array( |
|
'posts_per_page' => 1, |
|
'post__not_in' => array($args['post_id']) |
|
) |
|
); |
|
|
|
$prev_query = new WP_Query( |
|
array_merge($query_args, |
|
array( |
|
'order' => 'ASC', |
|
'date_query' => array( |
|
array( |
|
'after' => $current_post_date |
|
) |
|
) |
|
) |
|
) |
|
); |
|
|
|
$next_query = new WP_Query( |
|
array_merge($query_args, |
|
array( |
|
'order' => 'DESC', |
|
'date_query' => array( |
|
array( |
|
'before' => $current_post_date |
|
) |
|
) |
|
) |
|
) |
|
); |
|
|
|
wp_reset_postdata(); |
|
|
|
if( 'array' === $args['output'] ) |
|
{ |
|
return array( |
|
'prev_post_url' => isset($prev_query->posts[0]->ID) ? esc_url(get_permalink($prev_query->posts[0]->ID)) : null, |
|
'next_post_url' => isset($next_query->posts[0]->ID) ? esc_url(get_permalink($next_query->posts[0]->ID)) : null |
|
); |
|
} |
|
|
|
$output[]= '<nav class="nav-images">'; |
|
|
|
if( isset($prev_query->posts[0]) ) { |
|
$output[]= sprintf('<a href="%s" class="nav-images__btn prev"><span class="sr-only">%s</span></a>', esc_url(get_permalink($prev_query->posts[0]->ID)), __('Previous')); |
|
} |
|
|
|
if( isset($next_query->posts[0]) ) { |
|
$output[]= sprintf('<a href="%s" class="nav-images__btn next"><span class="sr-only">%s</span></a>', esc_url(get_permalink($next_query->posts[0]->ID)), __('Next')); |
|
} |
|
$output[]= '</nav>'; |
|
|
|
return apply_filters('px_get_custom_post_nav_output', implode("\n", $output)); |
|
} |