管理区域自定义类型按无标题和内容的元字段搜索

时间:2013-05-10 作者:user1117841

我有一个自定义的帖子类型,它使用了几个元字段。在管理领域,我希望能够通过这些元字段进行搜索。我目前已在我的职能中实现了这一点。php使用以下代码:

function custom_search_query( $query ) {
  if ( is_admin() && is_main_query() && $query->is_search ) {
    $query->set(\'meta_query\', array(
      "relation" => "OR",
      array(
        \'key\' => \'first_name\',
        \'value\' => $query->query_vars[\'s\'],
        \'compare\' => \'LIKE\'
      ),
      array(
        \'key\' => \'last_name\',
        \'value\' => $query->query_vars[\'s\'],
        \'compare\' => \'LIKE\'
      ),
      array(
        \'key\' => \'email\',
        \'value\' => $query->query_vars[\'s\'],
        \'compare\' => \'LIKE\'
      )
    ));
    $query->set(\'post_type\', \'application\'); // optional
  };
}
add_filter( \'pre_get_posts\', \'custom_search_query\');
问题是,对于这些代码,如果我搜索名称“walker”,并且在元字段中有与该标准匹配的自定义帖子类型的记录,则不会返回任何结果。出现这种情况的原因是执行的查询生成的SQL如下:

SELECT SQL_CALC_FOUND_ROWS wp_posts.ID FROM wp_posts 
INNER JOIN wp_postmeta ON (wp_posts.ID = wp_postmeta.post_id)
INNER JOIN wp_postmeta AS mt1 ON (wp_posts.ID = mt1.post_id)
INNER JOIN wp_postmeta AS mt2 ON (wp_posts.ID = mt2.post_id) WHERE 1=1
AND (((wp_posts.post_title LIKE \'%walker%\') OR (wp_posts.post_content LIKE  \'%walker%\'))) 
AND wp_posts.post_type = \'application\' AND (wp_posts.post_status =  \'publish\' 
OR wp_posts.post_status = \'future\' OR wp_posts.post_status = \'draft\' 
OR wp_posts.post_status = \'pending\' OR wp_posts.post_status = \'private\')
AND ((wp_postmeta.meta_key = \'first_name\' AND CAST(wp_postmeta.meta_value AS CHAR) LIKE  \'%walker%\')
OR (mt1.meta_key = \'last_name\' AND CAST(mt1.meta_value AS CHAR) LIKE \'%walker%\')
OR (mt2.meta_key = \'email\' AND CAST(mt2.meta_value AS CHAR) LIKE \'%walker%\') )   
GROUP BY wp_posts.ID ORDER BY wp_posts.post_date DESC LIMIT 0, 20
查询正在尝试搜索帖子标题和内容以及我的自定义字段。我不希望它在标题或内容中寻找匹配项。如何让查询停止这样做,从而返回aI想要的restuls?

1 个回复
SO网友:Jaz

有一个插件叫做Search everything, 在那里,您可以分解要搜索的内容。它可以自定义字段、帖子,当然还有标题。

结束