Created
January 21, 2025 19:32
-
-
Save infn8/740fb94440f2c4dac82e9d8a7edac4ff to your computer and use it in GitHub Desktop.
WordPress Previous and Next posts with the same taxonomy term
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Retrieve the adjacent posts for a specific custom post type and taxonomy. | |
* | |
* This function returns the previous and next posts based on the provided | |
* custom post type, taxonomy, and ordering by published date in descending order (newest first). | |
* | |
* @param int $post_id The ID of the current post. | |
* @param string $taxonomy The taxonomy to filter posts by. | |
* @param string $post_type The custom post type to query. | |
* | |
* @return array An associative array with 'previous' and 'next' keys containing post objects or null if not available. | |
* | |
* @example | |
* $adjacent_posts = get_adjacent_custom_posts(123, 'custom_taxonomy', 'custom_post_type'); | |
* if ($adjacent_posts['previous']) { | |
* echo 'Previous Post: ' . $adjacent_posts['previous']->post_title; | |
* } | |
* if ($adjacent_posts['next']) { | |
* echo 'Next Post: ' . $adjacent_posts['next']->post_title; | |
* } | |
*/ | |
function get_adjacent_custom_posts($post_id, $taxonomy, $post_type) { | |
$current_post = get_post($post_id); | |
if (!$current_post) { | |
return [ | |
'previous' => null, | |
'next' => null | |
]; | |
} | |
$args = [ | |
'post_type' => $post_type, | |
'posts_per_page' => -1, | |
'tax_query' => [ | |
[ | |
'taxonomy' => $taxonomy, | |
'field' => 'term_id', | |
'terms' => wp_get_post_terms($post_id, $taxonomy, ['fields' => 'ids']), | |
], | |
], | |
'orderby' => 'date', | |
'order' => 'DESC', | |
'fields' => 'ids', | |
]; | |
$posts = get_posts($args); | |
if (!$posts) { | |
return [ | |
'previous' => null, | |
'next' => null | |
]; | |
} | |
$current_index = array_search($post_id, $posts); | |
$previous_post_id = $current_index !== false && $current_index > 0 ? $posts[$current_index - 1] : null; | |
$next_post_id = $current_index !== false && $current_index < count($posts) - 1 ? $posts[$current_index + 1] : null; | |
$previous_post = $previous_post_id ? get_post($previous_post_id) : null; | |
$next_post = $next_post_id ? get_post($next_post_id) : null; | |
return [ | |
'previous' => $previous_post, | |
'next' => $next_post, | |
]; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment