The get_{$adjacent}_post_where WordPress PHP filter is used to modify the WHERE clause in the SQL for an adjacent post query. The dynamic part of the hook name, $adjacent
, refers to the type of adjacency, either ‘next’ or ‘previous’.
Possible hook names include:
- get_next_post_where
- get_previous_post_where
Usage
add_filter( 'get_next_post_where', 'your_custom_function', 10, 5 );
function your_custom_function( $where, $in_same_term, $excluded_terms, $taxonomy, $post ) { // Your custom code here return $where; }
Parameters
$where
(string): The WHERE 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 when$in_same_term
is true.$post
(WP_Post): WP_Post object.
More information
See WordPress Developer Resources: get_{$adjacent}_post_where
Examples
Exclude Posts with Certain Meta Key
add_filter( 'get_next_post_where', 'exclude_posts_with_meta_key', 10, 5 ); function exclude_posts_with_meta_key( $where, $in_same_term, $excluded_terms, $taxonomy, $post ) { global $wpdb; $where .= " AND $wpdb->posts.ID NOT IN ( SELECT post_id FROM $wpdb->postmeta WHERE meta_key = 'exclude_from_adjacent' )"; return $where; }
Show Posts from Same Category
add_filter( 'get_previous_post_where', 'same_category_previous_post', 10, 5 ); function same_category_previous_post( $where, $in_same_term, $excluded_terms, $taxonomy, $post ) { $where .= " AND post_type = 'post' AND post_status = 'publish'"; return $where; }
Exclude Posts with a Custom Post Type
add_filter( 'get_next_post_where', 'exclude_custom_post_type', 10, 5 ); function exclude_custom_post_type( $where, $in_same_term, $excluded_terms, $taxonomy, $post ) { $where .= " AND post_type != 'custom_post_type'"; return $where; }
Exclude Posts from Specific Categories
add_filter( 'get_previous_post_where', 'exclude_specific_categories', 10, 5 ); function exclude_specific_categories( $where, $in_same_term, $excluded_terms, $taxonomy, $post ) { $excluded_categories = array( 5, 12, 20 ); // Category IDs to exclude $where .= " AND term_taxonomy_id NOT IN (" . implode( ',', $excluded_categories ) . ")"; return $where; }
Show Posts with a Specific Post Status
add_filter( 'get_next_post_where', 'specific_post_status', 10, 5 ); function specific_post_status( $where, $in_same_term, $excluded_terms, $taxonomy, $post ) { $where .= " AND post_status = 'draft'"; return $where; }