我正在尝试向我的搜索添加自定义字段,这是我的SQL查询:
add_filter( 'posts_where', 'title_filter', 100000, 2 );
function title_filter($where, &$wp_query){
global $wpdb;
if(isset($_GET['s'])){
$searchWord = trim($_GET['s']," ");
$searchWhere = "AND ((
(wp_posts.post_title LIKE '% $searchWord %' OR wp_posts.post_title LIKE '$searchWord %' OR wp_posts.post_title LIKE '% $searchWord' OR wp_posts.post_title LIKE ' $searchWord' OR wp_posts.post_title LIKE '$searchWord' OR wp_posts.post_content LIKE '% $searchWord %' OR wp_posts.post_content LIKE '$searchWord %' OR wp_posts.post_content LIKE '% $searchWord' )
OR
(tter.name LIKE '% $searchWord % ' OR tter.name LIKE '$searchWord %' OR tter.name LIKE '% $searchWord')
OR
(ttax.description LIKE '% $searchWord %' OR ttax.description LIKE '$searchWord %' OR ttax.description LIKE '% $searchWord')
OR
(wp_posts.post_excerpt LIKE '% $searchWord %' OR wp_posts.post_excerpt LIKE '$searchWord %' OR wp_posts.post_excerpt LIKE '% $searchWord')
OR
(wp_postmeta.meta_value LIKE '% $searchWord %' OR wp_postmeta.meta_value LIKE '$searchWord %' OR wp_postmeta.meta_value LIKE '% $searchWord')
) AND
wp_posts.post_type IN ('post', 'page', 'attachment', 'reports', 'news-section', 'event-item', 'board-members', 'brand-logos', 'vacancies') AND ( wp_posts.post_status = 'future' OR wp_posts.post_author = 1 ) )";
return $searchWhere ;
}
return $where;
}
在添加此行OR (wp_postmeta.meta_value LIKE '% $searchWord %' OR wp_postmeta.meta_value LIKE '$searchWord %' OR wp_postmeta.meta_value LIKE '% $searchWord')
之前,我的代码完全适用于从标题或内容中搜索单词,但添加此行后无法正常工作,无法理解原因,因为我猜我写了正确的sql查询。
答案 0 :(得分:1)
尝试使用:pre_get_posts动作(在 function.php 中)
function filter_by_metavalue( $query ) {
if ( $query->is_main_query() ) {
$query->set('meta_key', 'YOUR KEY');
$query->set('meta_value', 'VALUE');
}}
add_action( 'pre_get_posts', 'filter_by_metavalue' );
答案 1 :(得分:0)
最后我找到了一个解决方案,安装了Relevanssi插件,并且还找到了一个技巧,在functions.php中写了它,现在我的自定义字段可以搜索:
add_filter('the_content', 'my_the_content');
function my_the_content($content) {
relevant custom fields so that relevanssi includes their content (inlcuding the real my content if specified)
if($post = is_the_content_called_by_relevanssi()){
$fields = array('customfield2','customfield2');
foreach($fields as $field){
$field_value = get_post_meta($post->ID, $field, TRUE);
$content .= ' '. ( is_array($field_value) ? implode(' ', $field_value) : $field_value );
}
}
else global $post;
return $content;
}
function is_the_content_called_by_relevanssi(){
if(!function_exists('relevanssi_init')) return false;
if (strnatcmp(phpversion(),'5.4.0') >= 0)
$trace = debug_backtrace(DEBUG_BACKTRACE_PROVIDE_OBJECT, 21);
else
$trace = debug_backtrace();
for($i = 0; $i<min(array(21,count($trace))); $i++){
if('relevanssi_do_excerpt' == $trace[$i]['function']) return $trace[$i]['args'][0];
}
return FALSE;
}