如果要搜索的自定义字段具有多个值,则Wordpress元查询

时间:2018-01-10 22:34:33

标签: php ajax wordpress

我有自定义帖子类型'位置'。这些位置适用于某些拉链,因此我在此帖子类型中有一个自定义字段“zip_codes”。我正在输入多个拉链到这个字段,如“10005,10006,10007,10008”。

在前端,我有一个zip输入框,调用ajax函数来查询位置。我将此输入框的值变为名为$zip_filter

的var

我的查询是这样的:

$zip_filter = $_POST['zip_filt'];

$args = array(
    'post_type' => 'locations', 
);  

if( isset( $_POST['zip_filt'] ))
    $args['meta_query'] = array(
        array(
            'key' => 'zip_codes',
            'compare' => 'IN',
            'value' => $zip_filter
        )
    );      

$query = new WP_Query( $args );
...

当我在zip_codes字段中有一个zip时,它有效但当我在那里有逗号分隔列表时,它没有。我无法弄清楚如何构建这个查询。

1 个答案:

答案 0 :(得分:0)

为meta_query添加find_in_set支持

/**
 * Class Add_Find_In_Set_Compare_To_Meta_Query
 */
class Add_Find_In_Set_Compare_To_Meta_Query {
  /**
   *
   */
  function __construct() {
    add_action( 'posts_where', array( $this, 'posts_where' ), 10, 2 );
  }
  /**
   * Adds value 'find_in_set' to meta query 'compare' var for WP_Query 
   *
   * query['meta_query'][{n}]['compare'] => 'find_in_set'
   * @example This will find in set where _related_post_ids is a string of comma separated post IDs.
   *
   *    $query = new WP_Query( array(
   *      'posts_per_page' => -1,
   *      'post_type' => 'post'
   *      'meta_query' => array(
   *        array(
   *          'key' => '_related_post_ids',
   *          'value' => $related_post->ID,
   *          'compare' => 'find_in_set',
   *        )
   *      ),
   *    );
   *
   * @param array $where
   * @param object $query
   *
   * @return array
   */
  function posts_where( $where, $query ) {
    global $wpdb;
    foreach( $query->meta_query->queries as $index => $meta_query ) {
      if ( isset( $meta_query['compare'] ) && 'find_in_set' == strtolower( $meta_query['compare'] ) ) {
        $regex = "#\(({$wpdb->postmeta}.meta_key = '" . preg_quote( $meta_query['key'] ) . "')" .
        " AND (CAST\({$wpdb->postmeta}.meta_value AS CHAR\)) = ('" . preg_quote( $meta_query['value'] ) . "')\)#";
        /**
         * Replace the compare '=' with compare 'find_in_set'
         */
        $where = preg_replace( $regex, "($1 AND FIND_IN_SET($3,$2))", $where );
      }
    }
    return $where;
  }
}
new Add_Find_In_Set_Compare_To_Meta_Query();

来源:https://gist.github.com/mikeschinkel/6402058