函数文档

get_meta_sql()

💡 云策文档标注

概述

get_meta_sql() 函数基于给定的元查询参数,生成用于附加到主查询的 SQL 子句。它通过实例化 WP_Meta_Query 类并调用其 get_sql() 方法来实现,返回包含 JOIN 和 WHERE 子句的数组。

关键要点

  • 函数接受元查询数组、元类型、主表名、主ID列名和可选上下文对象作为参数。
  • 返回一个数组,包含 'join' 和 'where' 键,分别对应 SQL 的 JOIN 和 WHERE 子句片段,若元类型无对应表则返回 false。
  • 内部依赖于 WP_Meta_Query 类,适用于处理 WordPress 中的自定义字段查询。

代码示例

$meta_query = array(
    array(
        'key' => 'color',
        'value' => 'blue',
        'compare' => 'NOT LIKE'
    )
);
global $wpdb;
$meta_sql = get_meta_sql( $meta_query, 'post', $wpdb->posts, 'ID' );
// 输出示例:
// Array
// (
//     [join] =>  INNER JOIN wp_postmeta ON (wp_posts.ID = wp_postmeta.post_id)
//     [where] =>  AND ( (wp_postmeta.meta_key = 'color' AND CAST(wp_postmeta.meta_value AS CHAR) NOT LIKE '%blue%') )
// )

📄 原文内容

Given a meta query, generates SQL clauses to be appended to a main query.

Description

See also

Parameters

$meta_queryarrayrequired
A meta query.
$typestringrequired
Type of meta.
$primary_tablestringrequired
Primary database table name.
$primary_id_columnstringrequired
Primary ID column name.
$contextobjectoptional
The main query object.

Default:null

Return

string[]|false Array containing JOIN and WHERE SQL clauses to append to the main query, or false if no table exists for the requested meta type.

  • join string
    SQL fragment to append to the main JOIN clause.
  • where string
    SQL fragment to append to the main WHERE clause.

Source

function get_meta_sql( $meta_query, $type, $primary_table, $primary_id_column, $context = null ) {
	$meta_query_obj = new WP_Meta_Query( $meta_query );
	return $meta_query_obj->get_sql( $type, $primary_table, $primary_id_column, $context );
}

Changelog

Version Description
3.2.0 Introduced.

User Contributed Notes

  1. Skip to note 2 content

    Example

     'color',
    		'value' => 'blue',
    		'compare' => 'NOT LIKE'
    	)
    );
    global $wpdb;
    $meta_sql = get_meta_sql( $meta_query, 'post', $wpdb->posts, 'ID' );

    Output depending on the meta query:

    Array
    (
        [join] =>  INNER JOIN wp_postmeta ON (wp_posts.ID = wp_postmeta.post_id)
        [where] =>  AND ( (wp_postmeta.meta_key = 'color' AND CAST(wp_postmeta.meta_value AS CHAR) NOT LIKE '%blue%') )
    )