我有一个自定义的帖子类型,我还需要一个自定义搜索。我想对文章标题和两个自定义字段进行索引/查询。我找到了只针对标题和自定义字段的解决方案,但不同时针对这两个字段,所以我尝试将它们结合起来。为什么这样不行?
function custom_search( $search, &$wp_query )
{
global $wpdb;
if ( empty( $search ) )
return $search; // skip processing - no search term in query
$q = $wp_query->query_vars;
$n = ! empty( $q[\'exact\'] ) ? \'\' : \'%\';
$search =
$searchand = \'\';
foreach ( (array) $q[\'search_terms\'] as $term ) {
$term = esc_sql( like_escape( $term ) );
$search .= "{$searchand}($wpdb->posts.post_title LIKE \'{$n}{$term}{$n}\')";
$searchand = \' AND \';
}
$searchand = \' OR \';
foreach ( (array) $q[\'search_terms\'] as $term ) {
$term = esc_sql( like_escape( $term ) );
$search .= "{$searchand}(($wpdb->m.meta_key = \'wpcf-kurzbeschreibung\') AND (m.meta_value LIKE \'{$n}{$term}{$n}\'))";
$searchand = \' AND \';
}
if ( ! empty( $search ) ) {
$search = " AND ({$search}) ";
if ( ! is_user_logged_in() )
$search .= " AND ($wpdb->posts.post_password = \'\') ";
}
return $search;
}
add_filter( \'posts_search\', \'custom_search\', 500, 2 );
SO网友:luke
在我的情况下,我使用自定义查询,以便只使用:
$query = new WP_Query(array(\'post_type\' => \'akteur\', \'meta_query\' => array(
\'relation\' => \'OR\',
array(\'key\' => \'wpcf-kurzbeschreibung\',\'compare\' => \'LIKE\',\'value\' => $suchbegriff),
array(\'key\' => \'wpcf-zusatzinfo\',\'compare\' => \'LIKE\',\'value\' => $suchbegriff)
)
));