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
  • 3
  • 11

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,562
  • 3
  • 23
  • 44