2012-12-17 109 views
1

我想通過自定義字段篩選搜索結果的WordPress:過濾搜索按自定義字段結果

我有一個自定義字段cp_city,我想的是,用戶過濾由城市的結果,所以我增加了一個城市下拉在搜索框旁邊,改變查詢來改變結果,但由於某些原因,它不起作用。

這裏是我試過

  <?php 
     $city = isset($_GET['city']) ? trim($_GET['city']) : ''; 
     $s = $_GET['s']; 

     $paged = (get_query_var('paged')) ? get_query_var('paged') : 1; 
     query_posts(array('s' => $s, 'scat' => $scat, 'post_type' => 'ads', 'ignore_sticky_posts' => 1, 'meta_key' => 'cp_state', 'meta_value' => $city, 'meta_compare' => 'LIKE', 'paged' => $paged, 'orderby' => 'rand')); 
     ?> 

我也試過

function SearchFilter($query) { 
if ($query->is_search) { 
    $query->set('meta_key','cp_state'); 
$query->set('meta_value','london'); 
} 
return $query; 
} 

add_filter('pre_get_posts','SearchFilter'); 

但兩者的嘗試都失敗了。任何人都可以找出正確的解決方案。

+0

在你的第二個代碼 - 元關鍵是 'cp_state' 或 'cp_city'? –

+0

我的元鍵是cp_state。 –

回答

1

你應該做的是這樣的:

<?php 
$city = isset($_GET['city']) ? trim($_GET['city']) : ''; 
$s = $_GET['s']; 

$paged = (get_query_var('paged')) ? get_query_var('paged') : 1; 
query_posts( 
    array(
     's' => $s, 
     'scat' => $scat, 
     'post_type' => 'ads', 
     'ignore_sticky_posts' => 1, 
     'meta_query' = > array(
      'key' => 'cp_city', 
      'value' => $city, 
      'compare' => 'LIKE' 
     ), 
     'paged' => $paged, 
     'orderby' => 'rand') 
    ); 

>