get_meta_sql()WP 3.2.0

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

1 time — 0.000172 sec (fast) | 50000 times — 4.48 sec (fast)

No Hooks.

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.

Usage

get_meta_sql( $meta_query, $type, $primary_table, $primary_id_column, $context );
$meta_query(array) (required)
A meta query.
$type(string) (required)
Type of meta.
$primary_table(string) (required)
Primary database table name.
$primary_id_column(string) (required)
Primary ID column name.
$context(object)
The main query object.
Default: null

Examples

0

#1 Demonstration of use

$meta_query = array(
	array(
		'key'     => 'key_name',
		'value' => 'field value',
		'compare' => '=' // optional, default is '=' or 'IN' (if value is an array)
	)
);

$mq_sql = get_meta_sql( $meta_query, 'post', 'wp_posts', 'ID' );

$mq_sql will contain:

Array
(
	[join] =>  INNER JOIN wp_postmeta ON ( wp_posts.ID = wp_postmeta.post_id )
	[where] =>  AND (
		( wp_postmeta.meta_key = 'key_name' AND CAST(wp_postmeta.meta_value AS CHAR) = 'field value' )
	)
)
0

#2 More examples [auto-translate]

See WP_Meta_Query

Notes

Changelog

Since 3.2.0 Introduced.

get_meta_sql() code WP 6.5.2

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