get_meta_sql()
Creates the JOIN and WHERE parts of the SQL query for metadata based on the provided parameters, which can be used in the main query.
This is a wrapper for the class WP_Meta_Query.
Uses: WP_Meta_Query()
1 time — 0.000172 sec (fast) | 50000 times — 4.48 sec (fast)
No Hooks.
Returns
String[]|false. An associative array with JOIN and WHERE keys:
array( 'join' => 'JOIN SQL string', 'where' => 'WHERE SQL string' )
Usage
get_meta_sql( $meta_query, $type, $primary_table, $primary_id_column, $context );
- $meta_query(array) (required)
- Query parameters. See the description of WP_Meta_Query.
- $type(string) (required)
- Type of metadata. For example: 'user', 'post', 'comment'.
A table with the name $type .'meta' must be registered in the $wpdb object, for example, if we specify 'foo' here, then the table $wpdb->foometa must exist. If such a table does not exist, this class will not work! - $primary_table(string) (required)
- Name of the primary table to which the metadata table relates. For example wp_posts, wp_comments, wp_users.
- $primary_id_column(string) (required)
- Name of the key column of the primary table specified in $primary_table. For wp_posts - ID, for wp_users - ID, for wp_comments - comment_ID.
- $context(object)
- Object of the main query. This parameter is not used anywhere and is passed to the filter
get_meta_sql.
Default: null
Examples
#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' ) ) )
#2 More examples
See WP_Meta_Query
Notes
- See: WP_Meta_Query
Changelog
| Since 3.2.0 | Introduced. |
get_meta_sql() get meta sql code WP 6.8.3
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 );
}