The get_{$adjacent}_post_join WordPress PHP filter allows you to modify the JOIN clause in the SQL query used for retrieving adjacent posts. The dynamic part of the filter’s name, $adjacent
, refers to the type of adjacency, either ‘next’ or ‘previous’. Possible hook names include:
- get_next_post_join
- get_previous_post_join
Usage
add_filter('get_next_post_join', 'your_custom_function', 10, 5); function your_custom_function($join, $in_same_term, $excluded_terms, $taxonomy, $post) { // your custom code here return $join; }
Parameters
$join
(string) – The JOIN clause in the SQL.$in_same_term
(bool) – Whether the post should be in the same taxonomy term.$excluded_terms
(int[]|string) – Array of excluded term IDs. Empty string if none were provided.$taxonomy
(string) – Taxonomy. Used to identify the term used when$in_same_term
is true.$post
(WP_Post) – WP_Post object.
More information
See WordPress Developer Resources: get_{$adjacent}_post_join
Examples
Modify JOIN clause to include custom post meta
Modify the JOIN clause to include a custom post meta field named ‘featured’.
add_filter('get_next_post_join', 'modify_adjacent_post_join', 10, 5); function modify_adjacent_post_join($join, $in_same_term, $excluded_terms, $taxonomy, $post) { $join .= " INNER JOIN wp_postmeta AS m ON p.ID = m.post_id AND m.meta_key = 'featured' "; return $join; }
Include only posts with specific custom field value
Retrieve only adjacent posts that have a custom field ‘color’ with a value of ‘red’.
add_filter('get_previous_post_join', 'filter_adjacent_post_by_color', 10, 5); function filter_adjacent_post_by_color($join, $in_same_term, $excluded_terms, $taxonomy, $post) { $join .= " INNER JOIN wp_postmeta AS m ON p.ID = m.post_id AND m.meta_key = 'color' AND m.meta_value = 'red' "; return $join; }
Exclude posts with a specific custom field value
Exclude adjacent posts that have a custom field ‘status’ with a value of ‘draft’.
add_filter('get_next_post_join', 'exclude_adjacent_post_by_status', 10, 5); function exclude_adjacent_post_by_status($join, $in_same_term, $excluded_terms, $taxonomy, $post) { $join .= " LEFT JOIN wp_postmeta AS m ON p.ID = m.post_id AND m.meta_key = 'status' "; return $join; }
Include posts from a specific author
Retrieve adjacent posts only from a specific author with an author ID of 5.
add_filter('get_previous_post_join', 'filter_adjacent_post_by_author', 10, 5); function filter_adjacent_post_by_author($join, $in_same_term, $excluded_terms, $taxonomy, $post) { $join .= " INNER JOIN wp_posts AS p2 ON p.post_author = p2.post_author AND p2.post_author = 5 "; return $join; }