使用WooCommerce产品搜索

时间:2015-12-18 06:09:53

标签: php wordpress search post woocommerce

我正在使用this code来搜索Wordpress / WooCommerce网站上的产品。
我的要求是URL就像" http://localhost/wp/?s=D34&post_type=product" 虽然s=D34是搜索字符串。

当用户搜索字符串时。将从所有默认字段+产品custom filed中搜索数据。以下代码适用于http://localhost/wp/?s=D34,但当&post_type=product与网址连接后,它会说enter image description here

代码如下

function cf_search_where( $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_value LIKE $1)", $where );
        $where .= " AND ($wpdb->posts.post_type = 'product') ";
    }

    return $where;
}
add_filter( 'posts_where', 'cf_search_where' );

这是为了防止不同的值

  function cf_search_distinct( $where ) {
        global $wpdb;
if ( is_search() ) {
    return "DISTINCT"; //to prevent duplicates
}

return $where;

}
add_filter( 'posts_distinct', 'cf_search_distinct' );

那么需要进行哪些修改?

URL http://localhost/wp/?orderby=price&post_type=product工作正常

但是http://localhost/wp/?s=D34&post_type=product

出了什么问题

1 个答案:

答案 0 :(得分:4)

试试这个

function cf_search_where( $where ) {
    global $pagenow, $wpdb;

    // a little debugging will help you..
    //print_r ($where);
    //die();

    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_value LIKE $1)", $where );
        $where .= " AND ($wpdb->posts.post_type = 'product') ";
    }

    return $where;
}
add_filter( 'posts_where', 'cf_search_where' );

根据您更新的问题。

如果您只使用print_r ($where);检查$where包含的值,您会看到类似的内容...

http://localhost/wp/?s=D34

AND (((wp1_posts.post_title LIKE '%D34%') OR (wp1_postmeta.meta_value LIKE '%D34%') OR (wp1_posts.post_content LIKE '%D34%'))) 
AND (wp1_posts.post_password = '') 
AND wp1_posts.post_type IN ('post', 'page', 'attachment', 'product') 
AND (wp1_posts.post_status = 'publish')

http://localhost/wp/?s=D34&post_type=product

AND (((wp1_posts.post_title LIKE '%D34%') OR (wp1_postmeta.meta_value LIKE '%D34%') OR (wp1_posts.post_content LIKE '%D34%'))) 
AND (wp1_posts.post_password = '') 
AND ( ( wp1_postmeta.meta_key = '_visibility' AND CAST(wp1_postmeta.meta_value AS CHAR) IN ('visible','search') ) ) 
AND wp1_posts.post_type = 'product' 
AND (wp1_posts.post_status = 'publish')

注意wp1_posts.post_type并获得提示..对自己保持灵活性并尝试调试。以上是没有$where .= " AND ($wpdb->posts.post_type = 'product') ";的结果。