The posts_join_request filter lets you modify the JOIN clause of a WordPress query, often used by caching plugins to optimize database queries.
Usage
add_filter('posts_join_request', 'your_custom_function', 10, 2);
function your_custom_function($join, $query) {
// your custom code here
return $join;
}
Parameters
- $join (string): The JOIN clause of the query.
- $query (WP_Query): The WP_Query instance, passed by reference.
More information
See WordPress Developer Resources: posts_join_request
Examples
Adding a custom table to the JOIN clause
Modify the JOIN clause to include a custom table for additional filtering.
add_filter('posts_join_request', 'add_custom_table_to_join', 10, 2);
function add_custom_table_to_join($join, $query) {
global $wpdb;
$join .= " LEFT JOIN {$wpdb->prefix}custom_table ON {$wpdb->prefix}posts.ID = {$wpdb->prefix}custom_table.post_id";
return $join;
}
Joining with postmeta table
Add postmeta table to the JOIN clause to filter posts based on a custom field.
add_filter('posts_join_request', 'join_with_postmeta', 10, 2);
function join_with_postmeta($join, $query) {
global $wpdb;
$join .= " INNER JOIN {$wpdb->postmeta} ON ({$wpdb->posts}.ID = {$wpdb->postmeta}.post_id)";
return $join;
}
Joining with taxonomy and term relationships tables
Join the taxonomy and term_relationships tables to filter posts by a custom taxonomy.
add_filter('posts_join_request', 'join_with_taxonomy', 10, 2);
function join_with_taxonomy($join, $query) {
global $wpdb;
$join .= " INNER JOIN {$wpdb->term_relationships} ON ({$wpdb->posts}.ID = {$wpdb->term_relationships}.object_id)";
$join .= " INNER JOIN {$wpdb->term_taxonomy} ON ({$wpdb->term_relationships}.term_taxonomy_id = {$wpdb->term_taxonomy}.term_taxonomy_id)";
return $join;
}
Joining with users table
Join the users table to filter posts by the author’s display name.
add_filter('posts_join_request', 'join_with_users', 10, 2);
function join_with_users($join, $query) {
global $wpdb;
$join .= " INNER JOIN {$wpdb->users} ON ({$wpdb->posts}.post_author = {$wpdb->users}.ID)";
return $join;
}
Joining with comments table
Join the comments table to filter posts based on the number of comments.
add_filter('posts_join_request', 'join_with_comments', 10, 2);
function join_with_comments($join, $query) {
global $wpdb;
$join .= " LEFT JOIN {$wpdb->comments} ON ({$wpdb->posts}.ID = {$wpdb->comments}.comment_post_ID)";
return $join;
}