posts_join is a WordPress PHP filter that lets you modify the JOIN clause of a query in a WordPress site.
Usage
add_filter('posts_join', 'my_custom_posts_join', 10, 2); function my_custom_posts_join($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
Examples
Include custom table in the query
To include a custom table in the query, modify the JOIN clause.
add_filter('posts_join', 'join_custom_table', 10, 2); function join_custom_table($join, $query) { global $wpdb; $join .= " LEFT JOIN {$wpdb->prefix}my_custom_table ON {$wpdb->prefix}posts.ID = {$wpdb->prefix}my_custom_table.post_id "; return $join; }
Filter posts by meta value
Filter posts based on a specific meta value.
add_filter('posts_join', 'join_post_meta', 10, 2); function join_post_meta($join, $query) { global $wpdb; $join .= " INNER JOIN {$wpdb->postmeta} ON ( {$wpdb->posts}.ID = {$wpdb->postmeta}.post_id ) "; return $join; }
Filter posts by custom taxonomy
Filter posts based on a custom taxonomy term.
add_filter('posts_join', 'join_custom_taxonomy', 10, 2); function join_custom_taxonomy($join, $query) { global $wpdb; $join .= " INNER JOIN {$wpdb->term_relationships} ON ({$wpdb->posts}.ID = {$wpdb->term_relationships}.object_id) "; return $join; }
Filter posts by multiple taxonomies
Filter posts based on multiple taxonomy terms.
add_filter('posts_join', 'join_multiple_taxonomies', 10, 2); function join_multiple_taxonomies($join, $query) { global $wpdb; $join .= " INNER JOIN {$wpdb->term_relationships} AS tr1 ON ({$wpdb->posts}.ID = tr1.object_id) "; $join .= " INNER JOIN {$wpdb->term_relationships} AS tr2 ON ({$wpdb->posts}.ID = tr2.object_id) "; return $join; }
Exclude posts with a specific meta key
Exclude posts that have a specific meta key.
add_filter('posts_join', 'exclude_posts_with_meta_key', 10, 2); function exclude_posts_with_meta_key($join, $query) { global $wpdb; $join .= " LEFT JOIN {$wpdb->postmeta} AS pm1 ON ({$wpdb->posts}.ID = pm1.post_id AND pm1.meta_key = 'my_meta_key') "; return $join; }