2012-03-21 130 views
1

我編寫了一個查詢,用於搜索所有包含X作爲元/自定義字段值的帖子。PHP/MySQL查詢在字段中查找字符串

// PSV National Query 
     if ($_POST['vehicleType'] == 'psv' && $_POST['coverageRegion'] == 'national') {   

      $customkey = 'vehicleType'; 
      $customvalue = $_POST['vehicleType']; 

      $customkey1 = 'coverageRegion'; 
      $customvalue1 = $_POST['coverageRegion']; 

      $customkey2 = 'locationType'; 
      $customvalue2 = $_POST['locationType']; 

      global $wpdb; 
      $my_posts = $wpdb->get_results(" 
       SELECT $wpdb->posts.* 
       FROM $wpdb->posts, $wpdb->postmeta, $wpdb->postmeta AS mt1 
       WHERE $wpdb->posts.ID = $wpdb->postmeta.post_id 

       AND $wpdb->postmeta.meta_key = '$customkey' 
       AND $wpdb->postmeta.meta_value = '$customvalue' 
       AND mt1.meta_key = '$customkey1' 
       AND mt1.meta_value = '$customvalue1' 
       AND mt2.meta_key = '$customkey2' 
       AND mt2.meta_value = '$customvalue2' 

       AND $wpdb->posts.post_status = 'publish' 
       AND $wpdb->posts.post_type = 'post' 
       ORDER BY $wpdb->posts.post_date DESC 
      "); 

      $args = array(
      'meta_query' => array(
      array(
       'key' => $customkey, 
       'value' => $customvalue, 
       'compare' => '=' 
      ), 
      array(
       'key' => $customkey1, 
       'value' => $customvalue1, 
       'compare' => '=' 
      ), 
      array(
       'key' => $customkey2, 
       'value' => $customvalue2, 
       'compare' => '=' 
      ) 
      ) 
      ); 
      $query = new WP_Query($args); 

      foreach ($query as $post) : 
      setup_postdata($post); 

      echo '<div><a href="'; 
      the_permalink(); 
      echo '"></div>'; 
      the_title(); 

      endforeach; 

     } 

現在對於我的文章,我有1個值爲每個元鍵,這工作正常,但我想有多個值。

例如...

「天然氣,電力,水」

當我添加多個值但該查詢返回空,我presumer它,因爲即時消息說,如果...

postmeta.meta_value = '$customvalue' 

任何人都可以告訴我哪裏會出錯嗎?

回答

0

爲什麼不使用內置的WP QUERY,它支持元字段數組運算符。

例如:

$query = new WP_Query(array( 
          'meta_key'  => 'color', 
          'meta_value' => 'blue', 
          'meta_compare' => '!=' 
         )); 

編號:http://codex.wordpress.org/Class_Reference/WP_Query#Custom_Field_Parameters

+0

我已經試過這@Wyck只是它似乎不變量在我的領域內搜索匹配... – Liam 2012-03-21 17:10:37

+0

您是否嘗試過使用'get_post_custom'輸出http://codex.wordpress.org/Function_Reference/get_post_custom,打開調試,http://debugggg.wordpress.com/ – Wyck 2012-03-21 17:14:57

0

如果您在查詢的where子句中使用多個匹配,則應該使用IN變量而不是=。

我在您的查詢在您使用$ customvalue看到的唯一排在這裏

AND $wpdb->postmeta.meta_value = '$customvalue' 

,則應該更換=至IN,並與一個單獨的值,引號「」像這樣的例子

AND $wpdb->postmeta.meta_value IN ('gas','electricity','water') 

我放棄了上面代碼中的$ customvalue,以使IN值的分隔符的點。

希望這會讓你走上正軌。

+0

感謝@guzzie中, 'customvalue' 是具有其值設置通過POST – Liam 2012-03-21 17:00:24