apply_filters_ref_array( ‘posts_join’, string $join, WP_Query $query )

Filters the JOIN clause of the query.

Parameters

$joinstring
The JOIN clause of the query.
$queryWP_Query
The WP_Query instance (passed by reference).

More Information

When you use the wp_query object to run a query, not all tables are queried by default. For example, a query on the blog archive will only query the posts table. If you wanted to display posts that have specific meta value you will have to alter the wp_query object to include the required meta key.

Source

$join = apply_filters_ref_array( 'posts_join', array( $join, &$this ) );

Changelog

VersionDescription
1.5.0Introduced.

User Contributed Notes

  1. Skip to note 2 content

    Example migrated from Codex:

    To include the required tables in the query use the posts_join filter.

    The below example adds a meta field for use in displaying search results.

    // Join for searching metadata
    function AIOThemes_joinPOSTMETA_to_WPQuery($join) {
        global $wp_query, $wpdb;
    
        if (!empty($wp_query->query_vars['s'])) {
            $join .= "LEFT JOIN $wpdb->postmeta ON $wpdb->posts.ID = $wpdb->postmeta.post_id ";
        }
    
        return $join;
    }
    
    add_filter('posts_join', 'AIOThemes_joinPOSTMETA_to_WPQuery');

    And then the specific search:

    function AIO_AlphabeticSearch_WhereString( $where, &$wp_query )
    {
        global $wpdb;
        if(isset($_GET['aioAlphaSearchMode']) && $_GET['aioAlphaSearchMode'] == 1){
    
            $searchAlphabet = esc_sql($_GET['s']); 
    
            $where .= ' AND ' . $wpdb->posts . '.post_title LIKE \''.$searchAlphabet.'%\' ';
    
            // use only if the post meta db table has been joined to the search tables using posts_join filter
            $where .= " AND ($wpdb->postmeta.meta_key = 'JDReview_CustomFields_ReivewOrNewsPostType' AND $wpdb->postmeta.meta_value = 'JDReview_PostType_ReviewPost') ";
            return $where;
        }
    }
    
    add_filter( 'posts_where', 'AIO_AlphabeticSearch_WhereString', 10, 2 );

You must log in before being able to contribute a note or feedback.