Make WordPress Core

Changeset 21185


Ignore:
Timestamp:
06/29/2012 07:59:29 PM (12 years ago)
Author:
nacin
Message:

Add NOT EXISTS to meta queries, allowing you to query for the non-existence of a meta key.

You could already use EXISTS by omitting a value to check.

props georgestephanis, scribu
fixes #18158

File:
1 edited

Legend:

Unmodified
Added
Removed
  • trunk/wp-includes/meta.php

    r20435 r21185  
    721721                $meta_type = 'CHAR';
    722722
     723            $meta_value = isset( $q['value'] ) ? $q['value'] : null;
     724
     725            if ( isset( $q['compare'] ) )
     726                $meta_compare = strtoupper( $q['compare'] );
     727            else
     728                $meta_compare = is_array( $meta_value ) ? 'IN' : '=';
     729
     730            if ( ! in_array( $meta_compare, array(
     731                '=', '!=', '>', '>=', '<', '<=',
     732                'LIKE', 'NOT LIKE',
     733                'IN', 'NOT IN',
     734                'BETWEEN', 'NOT BETWEEN',
     735                'NOT EXISTS'
     736            ) ) )
     737                $meta_compare = '=';
     738
    723739            $i = count( $join );
    724740            $alias = $i ? 'mt' . $i : $meta_table;
    725741
    726             // Set JOIN
     742            if ( 'NOT EXISTS' == $meta_compare ) {
     743                $join[$i]  = "LEFT JOIN $meta_table";
     744                $join[$i] .= $i ? " AS $alias" : '';
     745                $join[$i] .= " ON ($primary_table.$primary_id_column = $alias.$meta_id_column AND $alias.meta_key = '$meta_key')";
     746
     747                $where[$k] = ' ' . $alias . '.' . $meta_id_column . ' IS NULL';
     748
     749                continue;
     750            }
     751
    727752            $join[$i]  = "INNER JOIN $meta_table";
    728753            $join[$i] .= $i ? " AS $alias" : '';
     
    733758                $where[$k] = $wpdb->prepare( "$alias.meta_key = %s", $meta_key );
    734759
    735             if ( !isset( $q['value'] ) ) {
     760            if ( is_null( $meta_value ) ) {
    736761                if ( empty( $where[$k] ) )
    737762                    unset( $join[$i] );
    738763                continue;
    739764            }
    740 
    741             $meta_value = $q['value'];
    742 
    743             $meta_compare = is_array( $meta_value ) ? 'IN' : '=';
    744             if ( isset( $q['compare'] ) )
    745                 $meta_compare = strtoupper( $q['compare'] );
    746 
    747             if ( ! in_array( $meta_compare, array( '=', '!=', '>', '>=', '<', '<=', 'LIKE', 'NOT LIKE', 'IN', 'NOT IN', 'BETWEEN', 'NOT BETWEEN' ) ) )
    748                 $meta_compare = '=';
    749765
    750766            if ( in_array( $meta_compare, array( 'IN', 'NOT IN', 'BETWEEN', 'NOT BETWEEN' ) ) ) {
Note: See TracChangeset for help on using the changeset viewer.