更改搜索结果以处理当前WordPress中不起作用的帖子元字段

时间:2019-12-13 作者:AdamJones

我有以下代码(基于web上其他地方的示例),它肯定会更新查询,但不会返回任何结果。

我用错钩子了吗?

function custom_search_query( $q ) {
    if ( $q->is_search ) {
        $meta_query = $q->get( \'meta_query\' );
        $meta_query[] = array(
            \'key\' => \'custom_meta_key_name_here\',
            \'value\' => $q->query_vars[\'s\'],
            \'compare\' => \'LIKE\',
            \'type\'      => \'TEXT\',
        );
        $q->set( \'meta_query\', $meta_query );
    };
}
add_action( \'pre_get_posts\', \'custom_search_query\');

1 个回复
最合适的回答,由SO网友:AdamJones 整理而成

我通过以下功能组合实现了这一点(credit to this post):

function search_join_custom( $join ) {
    global $wpdb;
    if ( is_search() ) {
        $join .=\' LEFT JOIN \'.$wpdb->postmeta. \' ON \'. $wpdb->posts . \'.ID = \' . $wpdb->postmeta . \'.post_id \';
    }
    return $join;
}
add_filter(\'posts_join\', \'search_join_custom\' );
function search_where_custom( $where ) {
    global $pagenow, $wpdb;
    if ( is_search() ) {
        $where = preg_replace(
            "/\\(\\s*".$wpdb->posts.".post_title\\s+LIKE\\s*(\\\'[^\\\']+\\\')\\s*\\)/",
            "(".$wpdb->posts.".post_title LIKE $1) OR (".$wpdb->postmeta.".meta_key=\'YOUR_KEY_NAME\' AND ".$wpdb->postmeta.".meta_value LIKE $1)", $where );
    }
    return $where;
}
add_filter( \'posts_where\', \'search_where_custom\' );
function search_distinct_custom( $where ) {
    global $wpdb;
    if ( is_search() ) {
        return "DISTINCT";
    }
    return $where;
}
add_filter( \'posts_distinct\', \'search_distinct_custom\' );

相关推荐

Live search by custom tag

实时搜索:$the_query = new WP_Query( array( \'s\' => esc_attr( $_POST[\'keyword\'] ), \'post_type\' => \'custom_type\', \'sentence\' => \'true\' )); if( $the_query->have_posts() ) : while( $the_query->have_posts() ): $the_query->t