如何通过自定义字段值搜索特定自定义帖子类型的帖子,然后通过自定义字段复选框值“过滤”结果?

时间:2013-09-14 01:15:45

标签: mysql wordpress search custom-post-type custom-fields

我有自定义帖子类型(歌曲)和几个与之关联的自定义字段。其中一个自定义字段是复选框(sample_playlist),其余为文本字符串。

我添加了一个select元素,我在edit.php上使用复选框值来过滤结果?post_type = songs

add_filter( 'parse_query', array( &$this, 'wpse45436_posts_filter' ) );

function wpse45436_posts_filter( $query ){
// current page and post type checks omitted
    $query->query_vars['meta_key'] = 'sample_playlist';
    $query->query_vars['meta_value'] = 'on'; //these are the queries that get executed when filtering the posts that have the custom field checkbox checked
  }

当我只尝试根据复选框值过滤结果时,此方法正常。

也可以通过

在同一页面上搜索其他自定义字段值
 add_filter( 'posts_join', array( &$this, 'songs_search_join' ) );
 add_filter( 'posts_where', array( &$this, 'songs_search_where' ) );
function songs_search_join ($join){
    // current page, post type and $_GLOBAL['s'] checks omitted    
    $join .='LEFT JOIN '.$wpdb->postmeta. ' ON '. $wpdb->posts . '.ID = ' . $wpdb->postmeta . '.post_id ';
    return $join;
}
function songs_search_where( $where ){
    // current page, post type and $_GLOBAL['s'] checks omitted
    $where = preg_replace(
      "/\(\s*".$wpdb->posts.".post_title\s+LIKE\s*(\'[^\']+\')\s*\)/",
      "(".$wpdb->posts.".post_title LIKE $1) OR (".$wpdb->postmeta.".meta_value LIKE $1)", $where 
    );
    return $where;
}

当我只尝试按自定义字段值搜索字词时,搜索工作正常。

然而,当我尝试顺序使用这两个(即搜索然后过滤,反之亦然)时,我遇到了使用wp_postmeta的搜索连接问题以及"自定义字段复选框值& #34;也使用它。有没有解决方法,这将允许我顺序使用这两个?

我收到的错误:WordPress数据库错误不唯一的表/别名:' wp_postmeta'

生成的sql查询输出:

SELECT SQL_CALC_FOUND_ROWS wp_posts.ID FROM wp_posts INNER JOIN wp_postmeta ON (wp_posts.ID = wp_postmeta.post_id)LEFT JOIN wp_postmeta ON wp_posts.ID = wp_postmeta.post_id WHERE 1=1 AND (((wp_posts.post_title LIKE '%searchterm%') OR (wp_postmeta.meta_value LIKE '%searchterm%') OR (wp_posts.post_content LIKE '%searchterm%'))) AND wp_posts.post_type = 'songs' 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 = 'sample_playlist' AND CAST(wp_postmeta.meta_value AS CHAR) = 'on') ) ORDER BY wp_posts.post_date DESC LIMIT 0, 20

1 个答案:

答案 0 :(得分:2)

我需要在搜索中使用$ wpdb-> postmeta的别名:

add_filter( 'posts_join', array( &$this, 'songs_search_join' ) );
 add_filter( 'posts_where', array( &$this, 'songs_search_where' ) );
function songs_search_join ($join){
    // current page, post type and $_GLOBAL['s'] checks omitted    
    $join .='LEFT JOIN '.$wpdb->postmeta. ' p ON '. $wpdb->posts . '.ID = p.post_id ';
    return $join;
}
function songs_search_where( $where ){
    // current page, post type and $_GLOBAL['s'] checks omitted
    $where = preg_replace(
      "/\(\s*".$wpdb->posts.".post_title\s+LIKE\s*(\'[^\']+\')\s*\)/",
      "(".$wpdb->posts.".post_title LIKE $1) OR (p.meta_value LIKE $1)", $where 
    );
    return $where;
}