apply_filters_ref_array( 'posts_join', string $join, WP_Query $query )

Filters the JOIN clause of the query.


Parameters Parameters

$join

(string) The JOIN clause of the query.

$query

(WP_Query) The WP_Query instance (passed by reference).


Top ↑

More Information 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.


Top ↑

Source Source

File: wp-includes/class-wp-query.php

View on Trac



Top ↑

Changelog Changelog

Changelog
Version Description
1.5.0 Introduced.

Top ↑

User Contributed Notes User Contributed Notes

  1. Skip to note 1 content
    Contributed by stevenlinx

    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.