0

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

我添加了一个选择元素,并且在 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 的搜索连接以及使用它的“自定义字段复选框值”过滤器的问题。有没有办法解决这个问题,让我可以依次使用这两个?

我收到的错误: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
4

1 回答 1

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;
}
于 2013-09-14T01:37:23.360 回答