get_meta_sql( array $meta_query, string $type, string $primary_table, string $primary_id_column, object $context = null ): string[]|false

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

VersionDescription
3.2.0Introduced.

User Contributed Notes

  1. Skip to note 2 content

    Example

    <?php  
    $meta_query = array(
    	array(
    		'key' => '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%') )
    )

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