Using WordPress ‘get_meta_sql()’ PHP function

The get_meta_sql() WordPress PHP function generates SQL clauses based on a given meta query, which can then be appended to a main query.

Usage

get_meta_sql( $meta_query, $type, $primary_table, $primary_id_column, $context = null );

Example:

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

Parameters

  • $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) – Optional. The main query object. Default: null.

More information

See WordPress Developer Resources: get_meta_sql()

Examples

Filter posts by a custom field value

// Get posts with a specific custom field value
$meta_query = array(
  array(
    'key' => 'author_name',
    'value' => 'John Doe',
    'compare' => '='
  )
);
global $wpdb;
$meta_sql = get_meta_sql( $meta_query, 'post', $wpdb->posts, 'ID' );

Filter posts with a custom field value between two values

// Get posts with a custom field value between two values
$meta_query = array(
  array(
    'key' => 'price',
    'value' => array(100, 500),
    'compare' => 'BETWEEN'
  )
);
global $wpdb;
$meta_sql = get_meta_sql( $meta_query, 'post', $wpdb->posts, 'ID' );

Filter posts with multiple custom field conditions

// Get posts with multiple custom field conditions
$meta_query = array(
  'relation' => 'AND',
  array(
    'key' => 'color',
    'value' => 'red',
    'compare' => '='
  ),
  array(
    'key' => 'size',
    'value' => 'large',
    'compare' => '='
  )
);
global $wpdb;
$meta_sql = get_meta_sql( $meta_query, 'post', $wpdb->posts, 'ID' );

Filter posts with a custom field value that does not exist

// Get posts with a custom field value that does not exist
$meta_query = array(
  array(
    'key' => 'featured',
    'compare' => 'NOT EXISTS'
  )
);
global $wpdb;
$meta_sql = get_meta_sql( $meta_query, 'post', $wpdb->posts, 'ID' );

Filter users by a custom user meta value

// Get users with a specific custom user meta value
$meta_query = array(
  array(
    'key' => 'user_role',
    'value' => 'editor',
    'compare' => '='
  )
);
global $wpdb;
$meta_sql = get_meta_sql( $meta_query, 'user', $wpdb->users, 'ID' );