0

I am making a search function for searching products in woocommerce.
SO URL will be like "http://localhost/wp/?s=123&post_type=product".

User will search anything website will be searched and additionally product's custom field will be searched. This code work fine with http://localhost/wp/?s=123 but when "http://localhost/wp/?s=123&post_type=product is entered in url then it say No product is found.

Code is given below

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' );

So What modification is required?

URL http://localhost/wp/?orderby=date&post_type=product work fine

ALI
  • 339
  • 2
  • 10

1 Answers1

0

You write $wpdb->posts in "",thats why its not working. You check it below.

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' );
Domain
  • 11,110
  • 2
  • 22
  • 44
  • I'm positive that is not the problem. http://stackoverflow.com/questions/3446216/what-is-the-difference-between-single-quoted-and-double-quoted-strings-in-php – Reigel Dec 19 '15 at 05:52
  • another hint is that it works on `?s=123` and not on `?s=123&post_type=product` – Reigel Dec 19 '15 at 05:54