wordpress - 如何通过自定义字段值搜索特定自定义日志类型的日志,然后按自定义字段复选框值"filter" 进行搜索?

  显示原文与译文双语对照的内容
83 1

我有一个自定义的post类型( 歌曲) 和几个与之相关的自定义字段。自定义字段之一是复选框( 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_titles+LIKEs*('[^']+')s*)/",
"(".$wpdb->posts.".post_title LIKE $1) OR (".$wpdb->postmeta.".meta_value LIKE $1)", $where 
 );
 return $where;
}

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

但是,当我尝试使用这两个顺序的( 。IE 搜索然后过滤,反之亦然) 时,我使用wp_postmeta和"自定义字段复选框值"的筛选器运行了 Join 。这是否有一种方法可以以让我使用这两种方法?

收到的错误: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个回答

107 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_titles+LIKEs*('[^']+')s*)/",
"(".$wpdb->posts.".post_title LIKE $1) OR (p.meta_value LIKE $1)", $where 
 );
 return $where;
}
原作者:
...