钩子文档

posts_join

💡 云策文档标注

概述

posts_join 是一个 WordPress 过滤器,用于修改 WP_Query 查询中的 JOIN 子句。它允许开发者在执行数据库查询时添加额外的表连接,例如用于搜索元数据或自定义字段。

关键要点

  • 过滤器名称:posts_join,用于过滤查询的 JOIN 子句。
  • 参数:$join(JOIN 子句字符串)和 $query(WP_Query 实例,通过引用传递)。
  • 应用场景:默认查询可能不包含所有表(如 posts 表),使用此过滤器可扩展查询以包含其他表(如 postmeta 表)。
  • 版本历史:自 WordPress 1.5.0 引入。

代码示例

// 在搜索时连接 postmeta 表以包含元数据
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');

注意事项

  • 使用此过滤器时需确保全局变量 $wpdb 和 $wp_query 正确访问,以避免数据库错误。
  • 在修改 JOIN 子句后,可能需要配合其他过滤器(如 posts_where)来构建完整的查询条件。
  • 注意性能影响,添加不必要的表连接可能降低查询效率。

📄 原文内容

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

Version Description
1.5.0 Introduced.

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 );