我正在尝试过滤一个搜索,我想知道一个词是否在标题、内容或摘录中,但运气不佳,最后我被绊倒了。
$args = array(
\'post_type\' => \'post\',
\'posts_per_page\' => \'-1\',
\'search_prod_title\' => $_POST[\'wordToSearch\'],
\'post_status\' => \'publish\',
\'orderby\' => \'title\',
\'order\' => \'ASC\'
);
add_filter( \'posts_where\', \'title_filter\', 10, 2 );
add_filter( \'posts_where\', \'content_filter\', 10, 2 );
add_filter( \'posts_where\', \'excerpt_filter\', 10, 2 );
$posts = new WP_Query($args);
remove_filter( \'posts_where\', \'title_filter\', 10, 2 );
remove_filter( \'posts_where\', \'content_filter\', 10, 2 );
remove_filter( \'posts_where\', \'excerpt_filter\', 10, 2 );
我的过滤函数是:
function title_filter( $where, &$wp_query )
{
global $wpdb;
if ( $search_term = $wp_query->get( \'search_prod_title\' ) ) {
$where .= \' AND \' . $wpdb->posts . \'.post_title LIKE \\\'%\' . esc_sql( like_escape( $search_term ) ) . \'%\\\'\';
}
return $where;
}
function content_filter( $where, &$wp_query )
{
global $wpdb;
if ( $search_term = $wp_query->get( \'search_prod_content\' ) ) {
$where .= \' AND \' . $wpdb->posts . \'.post_content LIKE \\\'%\' . esc_sql( like_escape( $search_term ) ) . \'%\\\'\';
}
return $where;
}
function excerpt_filter( $where, &$wp_query )
{
global $wpdb;
if ( $search_term = $wp_query->get( \'search_prod_excerpt\' ) ) {
$where .= \' AND \' . $wpdb->posts . \'.post_excerpt LIKE \\\'%\' . esc_sql( like_escape( $search_term ) ) . \'%\\\'\';
}
return $where;
}
关键是,第一个过滤器功能工作正常,因此我可以按标题搜索,结果很好,但其余过滤器的结果错误或不工作。